The epilogue of These Savage Bones shows Esperanza and Alejandro happy and re-settled a year after the events of the story - and happily engaged, but the two of them had to go through a lot of crap to get there.
Subverted in Forever After, it seems as though the four great artifacts are kept in separate guarded locations so that when there is a great problem that needs the help of mighty heroes to solve they must go on grand quests and become better people for the experience. Actually, the artifacts just tear up the fabric of reality by being together for too long, and anything difficult for heroes to deal with will also be difficult for anyone else who wants the artifacts.
In Animorphs, after years of unimaginable pressure and War Is Hell torment, the kids become the greatest heroes in the history of humanity. However, only Marco, Cassie and Ax get to profit from it - Jake's clinically depressed due to his actions aboard the Pool ship, and Tobias struggles to live a solitary existence in the woods.
Hans Christian Andersen's The Little Mermaid. Oh, how heartbreakingly earned happy ending!
In Catherine and Her Fate, Catherine, given the choice between happiness in youth and old age, picked old age. She then finds that her Fate will see to it that she must have a truly abject life until then, but soldiers on.
The Ciaphas Cain series can fit into this trope. Cain sometimes gets really lucky, but we must recognize luck usually works as many times against him as in his favour, he still has to fight and figure out a way to save his life most of the time, but in the end, when he has managed to save the day (and usually the entire sector), he and his friends can go to a nice place to enjoy some amasec and tanna while tasting some delicacies. He managed to earn his retirement, which is to say something, considering the rate of casualties in the Imperial Guard, and after some decades he saved the world where he was (again), ensuring himself (again) his good retirement.
The novel Blood and Fire. The plot is set after the infamous Hive Helsreach battle and features Chaplain Grimaldus coming to the aid of the Celestial Lions Chapter. Bit of backstory here; the Celestial Lions are a Chapter that once took part in a battle against Chaos that the Inquisition ended early by Exterminatus. The Lions were horrified as this killed millions of innocents and they felt they could have saved them, so they call out the Inquisition for it. Even when the High Lords ignore them they don't stop, demanding the Inquisition be held accountable for a massacre. Things gradually turn against them as accidents in battle and disappearances of Chapter command whittle them down, until Armageddon where faulty intel and unusually accurate sniper attacks leave less than 100 of them alive. The last Apothecary in the Chapter is killed just as they reach safety, by someone shooting him in the temple with a drill-las. The Chapter is convinced they are doomed and resolve to die with their fallen brothers. Until Grimaldus says "screw that!" and leads the entire army of Hive Helsreach to support the Lions in avenging their honour against Ork Warboss Thogfang, which the Lions Pride-Leader Dubaku manages to kill. After this he orders the Lions to return to their home and start rebuilding, which is made easier when High Marshall Helbrecht arrives and gives Dubaku, the new Chapter Master, an ancient suit of Power Armour from the Heresy, a Strike Cruiser and an elite detachment of Black Templars to help rebuild this Chapter that put honour and what is right over their own existence. For once in 40k a story where honour and justice prevailed and the guys who did the right thing were rewarded for it, but sweet Emperor did they have to earn it. Additionally, there's the implication that due to the Templar's support the Celestial Lions will be able to rebuild properly, as the Inquisition learned the last time what happens when they mess with a First/Second Founding chapter with the First Battle for Armageddon. Especially when they're a chapter that is extremely close to each other, like the Black Templars and the Space Wolves.
K.A. Applegate's Everworld series. It's set in a world where all the gods and creatures from mythology exist, and as anyone who's read their mythology can tell you, that means horrible deaths and fates worse than death abound. And that's before Everworld is invaded by psychotic, heavily armed Neo-Nazis and an alien horde with their own god that eats other gods. For most of the series, the four teenagers who make up the main cast are barely able to keep themselves from killing each other, let alone staying alive, yet in the last book they actually manage to forge an alliance among the squabbling gods, start an industrial revolution in Everworld, and (while the series ends before the aforementioned Nazis and aliens can be defeated) the prospects for obtaining something close to peace are actually looking up.
This is one of the reasons a lot of readers find Terry Goodkind so irritating. Every single book of the Sword of Truth series makes it seem like the heroes have earned their happy ending, but the next book always reveals yet another previously-unexplained plot device that the author can use to torture them for another 600+ pages. The reason he does this is to avoid cliffhanger endings, but depending on your mileage, the cure might actually be worse than the disease.
Lloyd Alexander's The Chronicles of Prydain: Taran becomes the King of Prydain and marries the girl of his dreams, but only after losing several friends (and many others leaving forever) and having his idealistic image of a 'hero' shattered. Not only that, all the magic in the world is disappearing, leaving him to rule a much-more-mundane kingdom. Even then his ending isn't that happy, but the afterword seems to indicate that he at least accepts it, as his fading into legend would indicate an ending that may not necessarily be happy but at least positive.
Surprisingly, especially for an H.P. Lovecraft story, "The Dream Quest of Unknown Kadath" has this. The protagonist dispels Nyarlathotep's deception and narrowly avoids his doom, before waking up in the beautiful and architecturally extraordinary city of Boston, USA. Nyarlathotep then admits defeat, making this probably the happiest ending to any story in the Cthulu Mythos.
The Blade of the Flame: The evil wereshark plot is foiled and Makala is no longer possessed, but Asenka is dead, Makala is still a vampire, and the two male leads and their Love Interests are forced to go their separate ways.
Robin Hobb's later fantasy trilogiesThe Liveship Traders and The Tawny Man go through an incredibly dark journey and emerge to a more or less happy ending.
The Gormenghast series practically defines this trope. Titus goes through Hell and back, losing almost everybody he cares about to take down Steerpike, but in the end, he has a world to explore, a world to win.
World War Z chronicles the entirety of a Zombie Apocalypse, from the dark portents of danger, the manic reaction of humanity, the soulless survival techniques that many resorted to, and the horrors of the living dead. Despite this, it manages to have an undercurrent of hope that gets stronger, running side by side with the cynicism and blackness. After all, Humanity did win the war, in the end.
On a more individual level, Gara/Lara/Kirney's plotline through the Wraith Squadron books. She goes from an Imperial agent whose loyalty isn't deserved by those she serves, to a potential mole in Wraith Squadron, to a loyal member of said squadron who is in a relationship with a man, Myn, whose squadron she got destroyed when she was an Imperial. It probably comes as no surprise that her identity as a former Imperial Agent is revealed, and Myn ends up trying to kill her. Then she ends up back on an Imperial vessel, posing as a loyal soldier while actually sabotaging the ship for the benefit of the Republic. Then she's forced to fake her own death to avoid execution for treason from either side of the board. And all throughout this she suffers from Sanity Slippage due to having a Double Consciousness brought on by the stress of her Intelligence background. A (much) later book, Mercy Kill reveals that Myn found her, they got married, and had kids, but she went through a lot to be able to get there.
Both Sabriel and Touchstone in Sabriel are put through the metaphysical wringer. By the end, they've both lost their entire families and a lot of their friends to Kerrigor's undead minions. In the end, though Sabriel is saved from death by relatives in the beyond telling her it's not her time, and she and Touchstone are well on their way to a happily ever after. They even managed to save Mogget.
Stephen R. Donaldson's books are invariably like this.
Compared to some of John Brunner's other works (particularly The Sheep Look Up), The Shockwave Rider might have an ending that qualifies. "Well— how did you vote?"
Averted, Subverted, and Justified at the same time in Stephen King's The Dark Tower series. After a journeying for untold years to reach the Dark Tower (and consequently losing the greater number of his friends, lovers, and followers along the way) Roland FINALLY reaches the Dark Tower. However, upon reaching it he finds out that his existence is a cycle; he has made the journey to the tower an unknown number of times before this one. He is made to repeat his journey again and again until he finally learns his lesson (which is up to the reader to decide). He is, literally, sent back to the beginning of the series with no memory of what just happened. The trope is potentially played straight, however, by the fact that Roland may well be able to FINALLY complete his quest this time round.
Dragons of Requiem has The Dragon War trilogy, which has a surprisingly uplifting ending with no major casualties on the heroes' side, compared to the other trilogies' endings. Frey and Shari Cadigus are both dead, along with Leresy, who redeems himself before dying. Erry discovers who her real father is and lives with him and her half-sister. Valien is crowned king of Requiem and marries Kaelyn. And Tilla and Rune head back to their hometown Lynport, rebuild the town, and spend the rest of their life in peace.
Harry Potter goes through hell and loses several friends along the way, but in the end, he is able to defeat Voldemort through The Power of Love.
Mistborn — both the first and third books, actually. The second is more of a Downer Ending, since the Big Bad just escaped its imprisonment thanks to the heroine.
Melina Marchetta's spectacular On the Jellicoe Road (just Jellicoe Road in the US and UK) is an example of Earn Your Bittersweet Ending. Just about everybody who survives to the end has lost at least one loved one (often more), and the ending is still incredibly sad and unbelievably heartwarming.
Jane Eyre: "Reader, I married him." Jane Eyre had to struggle a lot before she could marry her one true love and enjoy a happy family life with him.
Honor Harrington really has to do this in one case especially. Over the course of "In Enemy Hands" and "Echoes of Honor" she is forced to surrender a ship captained by one of her oldest friends, with that friends' birthday party on board, captured, put into the hands of someone who is basically Himmler without the intelligence to not believe the propaganda, has her empathic and emotion - sharing treecat permanently crippled (found out later - he can no longer speak to other treecats), has her artificial eye and half her face electrocuted, is sentenced to death, sees her sworn retainers die in the (barely) successful escape attempt, loses an arm, lands on a prison planet, takes over said prison planet, builds a navy from all the ships stopping by at the prison planet, steals transports for all the people on the prison planet, and finally arrives back in the nearest friendly system to discover everyone thought her dead - and they'd held the funeral, and named ships after her, and she had a brother and sister that were planned to inherit her title. And somehow the whole thing is worthwhile in the simple sentence: "She was taking them home, and they were taking her home, and that was all in the universe that mattered." Yes, all that happens in between her leaving on an escort mission and getting home again.
The only person in the entire Silmarillion who gets an actual Happy Ending with no strings attached might be Tuor, who gets to sail to Valinor with his wife Idril, and becomes an honorary Elf by the grace of Ilúvatar.
The Choose Your Own Adventure series could give this trope a whole new meaning. As it stands now, you do have to go through a lot to get to even the good endings.
The Candy Shop War is surprisingly dark for a kid's book, and features, among other things, a Jerk Ass witch-hunter, a Bad Future, a ten-year-old getting trapped in an And I Must Scream scenario, and enough Body Horror for five books. However, it ends with all the kids back to normal, everyone friends, good changes on the horizon, and the Big Bad herself rendered harmless as a friendly little girl.
In Brandon Mull's other series, Fablehaven, this trope also occurs. The books get worse, and worse, and worse, and worse, culminating in the fifth book where, despite all their efforts otherwise, the demon prison opens and thousands of demons are released into the world. However, thanks to a Batman Gambit by the Fairy Queen, a lot of powerful allies, and some well-placed magic, the demons are reimprisoned, this time for a much, much longer era, the good guys win, and the ending is completely and utterly happy.
Blade of Tyshalle, to a degree that can neither be safely summarized without spoiling everything, nor summarized well in a manner that does the novel justice.
In the second Empire from the Ashes book, humanity suffers heavy losses against the genocidal Achuultani invaders, destroying the entire wave at the cost of many heroic sacrifices galore, the destruction of most of the military—including Colin's big damn reinforcements—and a death toll on Earth exceeding 500 million people.
Quantum Gravity: by the end of the fourth book, Lila has been tortured by elves, lost her trust in Sarasilien, the humans she worked with, and generally finds that it's going to be hard to grow up. She also literally goes through hell. Zal goes through hell, and then things get worse. But by the end, they're together, and Lila has figured out how to Be Herself. It's...less sappy in context.
In Vampire Academy, Rose finally gets her happy ending after one of her closest friends dying, nearly going insane, the love of her life being turned Strigoi and who gets eventually turned back after Rose nearly killing him twice, being tortured both through the bond with her best friend and actually tortured in person, getting accused of assassinating a monarch and nearly executed before she finds out that one of the people she trusts, likes and admires was the real killer and set her up to take the fall.
Maurice by E.M. Forster ends on this note. This was the reason why the book was not published until 51 years after it was written.
The cast in Dragons in Our Midst go through hell and back for their happy ending. And no, that's not speaking metaphorically, a few of them literally go through hell.
The Acts of Caine: what could count as a Downer Ending in another work is a rather happy ending in this book, compared to the hell the characters have been through.
In the Xanth this is pretty much the entire schtick behind Good Magician Humphery's missions: Successfully completing a Humphery-given task pretty much guarantees you (and those who helped you) a Happily Ever After. And most who get stuck with the year's service as payment for his answers end up better off for the experience. It's implied that many of Xanth's citizens know this for a fact and that's why so many are willing to give up a year's freedom (at a minimum) to petition Humphery.
Question Quest was originally about Lacuna trying for the trope; only thing is, Humphrey had been missing for a little over a decade (since the start of the 2nd Xanth series, Vale of the Vole), so with a little help from Grey (Humphrey's protegé), she tracks him down. Turns out he's been playing a waiting game with the Demon X(A/N)th in a quest to earn his happy ending. They help each other out to earn their respective endings.
Les MisÚrables: After 2000 pages leaning very, very hard to the cynical side, Valjean dies redeemed in his own eyes and Marius's, confident that he's kept his promises to Fantine and Bishop Myriel, and confident that his beloved Cosette will be happy.
John Taylor and Suzie Shooter from Simon R. Green's Nightside series. Though given how things work in the Nightside in general, and relating to John and Suzie both together and individually, bittersweet is almost more than they or pretty much everyone in the series would expect/hope for. Though in the Nightside, Bittersweet IS happy when you put things in perspective. Of course there's still one final book left to finish the series, so it's possible they might not even get that.
All of Ayn Rand's fiction, except for We The Living. Howard Roark gets his skyscraper, recognition of his artistic genius, and the girl in The Fountainhead; John Galt gets America, and the girl, and the heroes are setting out to rebuild a second golden age in Atlas Shrugged; and Equality 7-2521 escapes, gets the girl, and sets out to rebuild the world in Anthem.
The two characters who get the happiest endings in the first duology of the Arcia Chronicles are Shander Gardani, the Stoic Woobie who performs several Last Stands and is magically tortured for months by the Big Bad, and Princess Ilana, whose ambitions lead her to become the Big Bad's personal plaything and to lose everyone she loves. The two end up surprisingly Happily Married and found a dynasty that endures uncorrupted for many centuries.
Matteo in Someone Else's War has lost his home, his entire family, most of his classmates, one of his best friends, and by all accounts, his innocence. But thanks to some craftiness and cooperation from his friends (whom he never would have had had he spent the entire novel as cold and judgmental as he was toward the beginning), he manages to dismantle the world's largest army and send the Child Soldiers home.
In Sing You Home, Zoe and Vanessa fight in court with Zoe's born-again ex-husband Max, for their frozen embryos from their IVF treatment. Zoe and Vanessa want to have a family, and Max wants to give the embryos to his brother. Meanwhile, Max is in love with his brother's wife Liddy, and decides to give up the embryos because he doesn't want to see them happily raising his kids. In the end, they have a healthy girl, and Max gets Liddy.
This is how most Redwall books turn out. They're all happy endings but a lot of friends are lost, and it's never easy.
Trapped on Draconica: Team Good goes through a lot of hardship, a lot of pain, and a lot of suffering. Each one of them had a moment where they would have given up if not for the encouragement of the group. They all earn a happing ending.
Surely, the gods were merciful and loving. Surely they smiled upon this union, and he and his wives would live happily ever after.
At the end of The Wheel of Time books, millions are dead, many hundreds of thousands in the Last Battle alone, but they've defeated or dealt with the all of the Forsaken, crushed the army of Shadowspawn, Darkfriends and Dreadlords, and Re-sealed the Dark One. They've lost a lot of people on the way, but they have an Age of prosperiety awaiting them.
Nowhere is this more exemplified than with Rand, who after an absurd amount of It Sucks to Be the Chosen One, he gets to walk away in a new body free of pain or maiming, mostly anonymous, free of the responsibility that was constantly wearing away at his sanity, with new Reality Warper powers at the cost of his old abilities, and begins Walking the Earth.
The title character of Horatio Hornblower. From midshipman to admiral, he risks death daily, witnesses men die in horrible ways, loses a ship, loses several good officers, his first two children die of smallpox, he gets typhus in Russia, and his career is put at risk many times. Most of all, his "accursed unhappy temperament" prevents him from ever enjoying his many accomplishments because he'll always figure out a way to think of himself as a failure. But in the short story "The Last Encounter," Hornblower is retired, long since Happily Married to Lady Barbara, and finally happy and content for possibly the first time ever.
Swedish writer Simona Ahrnstedt does this in her debut novel Íverenskommelser. The poor female lead, Beatrice, has to suffer five years of abuse from her tyrannical uncle. And then he bullies his young niece into a marriage with a man, who's like forty years older than her and treats women like they're dirt under his shoes. So yeah, Beatrice is thrown into the mercy of another creep, who manages to brutally rape and batter her before he suddenly dies! Let's just hope that it was a really painful death... The story ends with Beatrice finally getting married to Seth, her love interest. But as they needed twenty months of suffering to get there, the happy ending sure was overdue...
After all the horror of their lives in The Kingdom of Little Wounds, Midi and Ava escape court, raise Midi's daughter together, and become wise women so they can be independent from all the men who have used them.
Several characters in The Night Angel Trilogy get their happy endings, but the cost is very high in a very dark setting. Word of God is that the contrast and suffering are what make choosing the right thing meaningful.
Nearly every book by Tim Powers runs on this trope, and few of his characters ever survive their arc without making some major sacrifice along the way, be it of blood, love, flesh, or memory.
Probably the second most prominent feature of the works of Jack Chalker. Though they're often remembered more for their Author Appeal, all of the Gender Benders, Viral Transformations, Baleful Polymorphs and just plain mutilations mean that it's a rare Chalker hero or heroine who survives their adventures physically or psychologically intact. There's even a soliloquy to this effect at the end of The Messiah Choice where a side character tells the hero (who had his genitals torn off while defeating the Big Bad, who may have been the Devil incarnate) that real sacrifices must be horrific by definition and anything that isn't painful, life-altering and above all permanent doesn't count as a true sacrifice.
The Fifth Sacred Thing by Starhawk, is about an egalitarian, multi-racial, decentralist, eco-feminist community in near-future California, fighting off an invasion from a fascist, white supremacist, male supremacist regime. The author is unflinching and disturbingly graphic in her depiction of the fascists' brutal repression (a scene late in the book depicts one of the foot soldiers snapping and slaughtering nearly an entire family, the last victim being an eight-year-old), and her protagonists go through immense physical, emotional, and psychological trauma over the course of the story. But they see it through, drive off the fascists, and the book closes with the promise of healing for both the main characters and their community. The message of the book is that humanity's better nature can win out against its worst in the end, but the price of struggle is very high.
In the The Iron Teeth web serial Blacknail the goblin goes through a lot more hardship, anguish, and grief than is really necessary.
In Warrior Cats, by the end of The Last Hope, every character has gone to hell and back (sometimes literally), but they still pull through and earn happy endings for themselves and all the Clans. The Clans have survived nearly being taken over by Tigerstar, almost being killed or driven out of the forest by BloodClan, the destruction of the forest by Twolegs and the resulting starvation and journey to the new territories, and the Dark Forest (feline hell)'s attempt at destroying the Clans. Not to mention all the hardships and heartbreak in between.
Harlan Ellison's 1961 novel Spider Kiss is a dark, cynical take on The Power of Rock where all the major characters are morally compromised, but protagonist Shelly Morgenstern manages to redeem himself. Throughout most of the story, Shelly is publicist for sociopathic singing star Stag Preston. This usually means keeping Stag's attempted rapes and drunken rampages out of the press, causing Shelly to become increasingly disgusted with both Stag and himself until he finally quits. Eventually, Stag's career tanks and he winds up singing at a New Orleans strip club, where he has a chance meeting with Shelly. Stag tells Shelly that if they renew their relationship, they could both return to the top. Shelly knows Stag is right, but he also knows that Stag is still a horrible person who doesn't deserve a second chance. Therefore, Shelly leaves Stag in the gutter where he belongs, regaining his self-respect in the process.
Sans Famille: Remi's misfortune starts with finding out he is adopted. Then he is sold by his abusive adoptive father to a travelling musician named Vitalis, but just when he begins to consider the man a surrogate parent, he loses Vitalis (and many of his animal companions) during a harsh winter. He is then taken in by a loving family named the Acquins, but loses them too when the father of the family, Pierre, is send to jail due to an unpaid debt. He finally appears to find his real family, the Driscolls, but they are cold towards him and even frame him for a robbery. But in the end, he finds his real mother and brother and inherits the family fortune his late father left him.
Each of the The Chronicles of Thomas Covenant play this trope so well that by the time readers have reached the climax it's nearly impossible to believe there could even be a happy ending. Not only are there happy endings, the happiness of the ending to each story arc escalates along with the scale of the threats and suffering the heroes are forced to contend with. Andtheyputupwithalot.
Exceptionally for an epic, The Divine Comedy ends happily with the protagonist having risen above the darkness of Earth, the torments of Hell, and the fires of Purgatory to fully encounter God. The last canto is taken up with Dante apologizing for his inability to describe how perfect the Love of God is and using every device he can to praise that One who is Three.