Web Api

All the world now is on-line

Let's create web (api)

#01 Creat new Web API project

Alt text

Alt text

In next step leave everything as it is

Alt text

#02 Now let's explore the project a bit

Alt text

#02.1 Run the app

Alt text

#02.2 Test it

Alt text

#02.3 Let's explore

Now we have fully functional application - now we have to turn it into what we realy want

#03 My Library Web Api project

#03.1 Let's clean a bit

Delete all not necessary stuff

Alt text

Alt text

temporarly change the Get method (to get rid of the error)

Alt text

#03.2 Rename the Controller.cs

Alt text

We could have create a new one - but like this will save a bit of time

Give it a name MyLibraryController.cs (Don't forget to keep the "Controller" ending)

Confirm renaming all

Alt text

#03.3 For now we don't need logger - comment it out (we can resurect it later)

Alt text

using Microsoft.AspNetCore.Mvc;

namespace AbcItWebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
            public class MyLibraryController : ControllerBase
    {
            //private readonly ILogger<MyLibraryController> _logger;

            //public MyLibraryController(ILogger<MyLibraryController> logger)
            //{
            //    _logger = logger;
            //}

        [HttpGet(Name = "GetMyLibrary")]
            public IEnumerable<string> Get()
        {
            return ["A", "B", "C", "I", "T"];
        }
    }
}

#03.4 Run the API again and check it works as expected

#04 Now we need to return something more meaningfull - our books

#04.1 - Create new folder Models

#04.2 - Create new class BookModel

Alt text

Now you are thinking - why not to copy-paste the model from the previous exercise 😆. Sure - we could reuse it - but the FE expects us to return a bit adjusted model. Luckily we don't need to write it manually.

#04.3 - Use the (well know) .json as input

[
            {
            "id": "1",
            "name": "Harry Potter and the Order of the Phoenix",
            "author": "J. K. Rowling",
            "genre": "Fantasy novel",
            "price": "€13.70",
            "imgUrl": "images/1.jpg",
            "url": "https://www.amazon.com/Harry-Potter-Order-Phoenix-Book/dp/043935806X",
            "backgroundColor": "#145E8C",
            "textColor": "#C1E7FF",
            "about": "As his fifth year at Hogwarts School of Witchcraft and Wizardry approaches, 15-year-old Harry Potter is in full-blown adolescence, complete with regular outbursts of rage, a nearly debilitating crush, and the blooming of a powerful sense of rebellion. It's been yet another infuriating and boring summer with the despicable Dursleys, this time with minimal contact from our hero's non-Muggle friends from school. Harry is feeling especially edgy at the lack of news from the magic world, wondering when the freshly revived evil Lord Voldemort will strike. Returning to Hogwarts will be a relief... or will it?<br /><br />The fifth book in J.K. Rowling's Harry Potter series follows the darkest year yet for our young wizard, who finds himself knocked down a peg or three after the events of last year. Somehow, over the summer, gossip (usually traced back to the magic world's newspaper, the Daily Prophet) has turned Harry's tragic and heroic encounter with Voldemort at the Triwizard Tournament into an excuse to ridicule and discount the teen. Even Professor Dumbledore, headmaster of the school, has come under scrutiny by the Ministry of Magic, which refuses to officially acknowledge the terrifying truth that Voldemort is back. Enter a particularly loathsome new character: the toadlike and simpering ('hem, hem') Dolores Umbridge, senior undersecretary to the Minister of Magic, who takes over the vacant position of Defense Against Dark Arts teacher--and in no time manages to become the High Inquisitor of Hogwarts, as well.<br /><br />Life isn't getting any easier for Harry Potter. With an overwhelming course load as the fifth years prepare for their Ordinary Wizarding Levels examinations (O.W.Ls), devastating changes in the Gryffindor Quidditch team lineup, vivid dreams about long hallways and closed doors, and increasing pain in his lightning-shaped scar, Harry's resilience is sorely tested..."
            },
            {
            "id": "2",
            "name": "The Alchemist",
            "author": "Paulo Coelho",
            "genre": "Psychological novel",
            "price": "€9.90",
            "imgUrl": "images/2.jpg",
            "url": "https://www.amazon.com/Alchemist-Paulo-Coelho/dp/0722532938/",
            "backgroundColor": "#F5CC4D",
            "textColor": "#6F5401",
            "about": "Like the one-time bestseller Jonathan Livingston Seagull, The Alchemist presents a simple fable, based on simple truths and places it in a highly unique situation. And though we may sniff a bestselling formula, it is certainly not a new one: even the ancient tribal storytellers knew that this is the most successful method of entertaining an audience while slipping in a lesson or two. Brazilian storyteller Paulo Coehlo introduces Santiago, an Andalusian shepherd boy who one night dreams of a distant treasure in the Egyptian pyramids. And so he's off: leaving Spain to literally follow his dream.<br /><br />Along the way he meets many spiritual messengers, who come in unassuming forms such as a camel driver and a well-read Englishman. In one of the Englishman's books, Santiago first learns about the alchemists--men who believed that if a metal were heated for many years, it would free itself of all its individual properties, and what was left would be the 'Soul of the World.' Of course he does eventually meet an alchemist, and the ensuing student-teacher relationship clarifies much of the boy's misguided agenda, while also emboldening him to stay true to his dreams. 'My heart is afraid that it will have to suffer,' the boy confides to the alchemist one night as they look up at a moonless night."
            },
            {
            "id": "3",
            "name": "Killing Moon",
            "author": "Jo Nesbo",
            "genre": "Thriller",
            "price": "€24.90",
            "imgUrl": "images/3.jpg",
            "url": "https://www.amazon.com/Killing-Moon/dp/1787303780",
            "backgroundColor": "#005660",
            "textColor": "#A9D9DF",
            "about": "This killer will get inside your head.<br /><br />Two young women are missing. Strangers to each other, but last seen at the same party. When the body of one of them is found with fresh stitches along her hairline the hunt is on to find a murderer with very particular tastes.<br /><br />Catching this criminal calls for a detective with a very particular mind<br /><br />Only Harry Hole can stop this ingenious psychopath. But Harry is gone: struck off the force, down and out in LA. It seems like nothing can entice him back to Oslo. Until someone close to him comes under threat.<br /><br />But there is more to this case than meets the eye and the clock is ticking down to find the other missing girl, before the body count rises.<br /><br />This killer has got inside Harry's head. And now he's coming for YOU."
            },
            {
            "id": "4",
            "name": "The Library of Heartbeats",
            "author": "Laura Imai Messina",
            "genre": "Novel",
            "price": "€13.10",
            "imgUrl": "images/4.jpg",
            "url": "https://www.amazon.com/Library-Heartbeats-heart-rending-Japanese-set-international-ebook/dp/B0C96FMRG3",
            "backgroundColor": "#FBA5C8",
            "textColor": "#87214A",
            "about": "To find what you have lost, you must listen to your heart . . .<br /><br />On the peaceful Japanese island of Teshima there is a library of heartbeats, a place where the heartbeats of visitors from all around the world are collected. In this small, isolated building, the heartbeats of people who are still alive or have already passed away continue to echo.<br /><br />Several miles away, in the ancient city of Kamakura, two lonely souls meet: Shuichi, a forty-year-old illustrator, who returns to his home-town to fix up the house of his recently deceased mother, and eight-year-old Kenta, a child who wanders like a shadow around Shuichi's house.<br /><br />Day by day, the trust between Shuichi and Kenta grows until they discover they share a bond that will tie them together for life. Their journey will lead them to Teshima and to the library of heartbeats . . ."
            },
            {
            "id": "5",
            "name": "Red Side Story",
            "author": "Jasper Fforde",
            "genre": "Science fiction fantasy",
            "price": "€19.40",
            "imgUrl": "images/5.jpg",
            "url": "https://www.amazon.com/Red-Side-Story-long-awaited-bestselling-ebook/dp/B09RPG3XMN",
            "backgroundColor": "#E4CD00",
            "textColor": "#615700",
            "about": "Imagine a world where your position in society depended on what bit of the colour spectrum you could see. This is the world inhabited by Eddie Russett (red, middle-level) and Jane Grey (monochromatic, lowest in society). Eddie and Jane must negotiate the delicate Chromatic politics of society to find out what the 'Something that Happened' actually was, how society got to be this way, and crucially, is there Somewhere Else beyond their borders - and if there is, could there be Someone Else, too, someone whose unseen hand has been guiding the fortunes and misfortunes of the nation for the past 500 years?<br /><br />It's a tale of a young couple's thirst for justice and answers in an implacably rigid society, where the prisoners are also the guards, and cages of convention bind the citizens to only one way of thinking - or suffer the consequences..."
            },
            {
            "id": "6",
            "name": "Two Can Keep a Secret",
            "author": "Karen M. McManus",
            "genre": "Thriller",
            "price": "€21.60",
            "imgUrl": "images/6.jpg",
            "url": "https://www.amazon.com/TWO-KEEP-SECRET-Karen-McManus/dp/0141375655",
            "backgroundColor": "#4CA7A8",
            "textColor": "#003638",
            "about": "Echo Ridge is small-town America. Ellery's never been there, but she's heard all about it. Her aunt went missing there at age seventeen. And only five years ago, a homecoming queen put the town on the map when she was killed. Now Ellery has to move there to live with a grandmother she barely knows.<br /><br />The town is picture-perfect, but it's hiding secrets. And before school even begins for Ellery, someone's declared open season on homecoming, promising to make it as dangerous as it was five years ago. Then, almost as if to prove it, another girl goes missing.<br /><br />Ellery knows all about secrets. Her mother has them; her grandmother does too. And the longer she's in Echo Ridge, the clearer it becomes that everyone there is hiding something. The thing is, secrets are dangerous--and most people aren't good at keeping them. Which is why in Echo Ridge, it's safest to keep your secrets to yourself."
            },
            {
            "id": "7",
            "name": "The Hobbit",
            "author": "J. R. R. Tolkien",
            "genre": "Fantasy",
            "price": "€9.20",
            "imgUrl": "images/7.jpg",
            "url": "https://www.amazon.com/Hobbit-J-R-R-Tolkien/dp/0618260307",
            "backgroundColor": "#005931",
            "textColor": "#9EDABF",
            "about": "'In a hole in the ground, there lived a hobbit.' So begins one of the most beloved and delightful tales in the English language.<br /><br />Set in the imaginary world of Middle-earth, at once a classic myth and a modern fairy tale, J.R.R. Tolkien's The Hobbit is one of literature's most enduring and well-loved novels. The text in this 372-page paperback edition is based on that first published in Great Britain by Collins Modern Classics and includes a note on the text by Douglas A. Anderson.<br /><br />Bilbo Baggins is a hobbit who enjoys a comfortable, unambitious life, rarely traveling any farther than his pantry or cellar. But his contentment is disturbed when the wizard Gandalf and a company of dwarves arrive on his doorstep one day to whisk him away on an adventure. They have launched a plot to raid the treasure hoard guarded by Smaug the Magnificent, a large and very dangerous dragon.<br /><br />Bilbo reluctantly joins their quest, unaware that on his journey to the Lonely Mountain he will encounter both a magic ring and a frightening creature known as Gollum."
            },
            {
            "id": "8",
            "name": "The Subtle Art of Not Giving a F*ck",
            "author": "Mark Manson",
            "genre": "Self-help",
            "price": "€17.60",
            "imgUrl": "images/8.jpg",
            "url": "https://www.amazon.com/Subtle-Art-Not-Giving-Counterintuitive/dp/0062641549",
            "backgroundColor": "#231E20",
            "textColor": "#96898E",
            "about": "For decades, we’ve been told that positive thinking is the key to a happy, rich life. 'F**k positivity,' Mark Manson says. 'Let’s be honest, shit is f**ked and we have to live with it.' In his wildly popular Internet blog, Manson doesn’t sugarcoat or equivocate. He tells it like it is—a dose of raw, refreshing, honest truth that is sorely lacking today. The Subtle Art of Not Giving a F**k is his antidote to the coddling, let’s-all-feel-good mindset that has infected modern society and spoiled a generation, rewarding them with gold medals just for showing up.<br /><br />Manson makes the argument, backed both by academic research and well-timed poop jokes, that improving our lives hinges not on our ability to turn lemons into lemonade, but on learning to stomach lemons better. Human beings are flawed and limited—'not everybody can be extraordinary, there are winners and losers in society, and some of it is not fair or your fault.' Manson advises us to get to know our limitations and accept them. Once we embrace our fears, faults, and uncertainties, once we stop running and avoiding and start confronting painful truths, we can begin to find the courage, perseverance, honesty, responsibility, curiosity, and forgiveness we seek.<br /><br />There are only so many things we can give a f**k about so we need to figure out which ones really matter, Manson makes clear. While money is nice, caring about what you do with your life is better, because true wealth is about experience. A much-needed grab-you-by-the-shoulders-and-look-you-in-the-eye moment of real-talk, filled with entertaining stories and profane, ruthless humor, The Subtle Art of Not Giving a F*ck is a refreshing slap for a generation to help them lead contented, grounded lives."
            },
            {
            "id": "9",
            "name": "House of Earth and Blood",
            "author": "Sarah J. Maas",
            "genre": "Science fiction fantasy",
            "price": "€25.50",
            "imgUrl": "images/9.jpg",
            "url": "https://www.amazon.com/House-Earth-Blood-Crescent-City/dp/1635574048",
            "backgroundColor": "#8D2D26",
            "textColor": "#FFD1CE",
            "about": "Bryce Quinlan had the perfect life-working hard all day and partying all night-until a demon murdered her closest friends, leaving her bereft, wounded, and alone. When the accused is behind bars but the crimes start up again, Bryce finds herself at the heart of the investigation. She'll do whatever it takes to avenge their deaths.<br /><br />Hunt Athalar is a notorious Fallen angel, now enslaved to the Archangels he once attempted to overthrow. His brutal skills and incredible strength have been set to one purpose-to assassinate his boss's enemies, no questions asked. But with a demon wreaking havoc in the city, he's offered an irresistible deal: help Bryce find the murderer, and his freedom will be within reach.<br /><br />As Bryce and Hunt dig deep into Crescent City's underbelly, they discover a dark power that threatens everything and everyone they hold dear, and they find, in each other, a blazing passion-one that could set them both free, if they'd only let it.<br /><br />With unforgettable characters, sizzling romance, and page-turning suspense, this richly inventive new fantasy series by #1 New York Times bestselling author Sarah J. Maas delves into the heartache of loss, the price of freedom-and the power of love."
            },
            {
            "id": "10",
            "name": "It",
            "author": "Stephen King",
            "genre": "Horror novel",
            "price": "€19.60",
            "imgUrl": "images/10.jpg",
            "url": "https://www.amazon.com/King-Stephen/dp/1444707868",
            "backgroundColor": "#20381E",
            "textColor": "#AFB5AE",
            "about": "Derry, Maine is just an ordinary town: familiar, well-ordered for the most part, a good place to live. It is a group of children who see - and feel - what makes Derry so horribly different. In the storm drains, in the sewers, IT lurks, taking on the shape of every nightmare, each one's deepest dread. Sometimes is appears as an evil clown named Pennywise and sometimes IT reaches up, seizing, tearing, killing... Time passes and the children grow up, move away and forget. Until they are called back, once more to confront IT as IT stirs and coils in the sullen depths of their memories, emerging again to make their past nightmares a terrible present reality."
            }
]

If we now replace our .json content from the previous project and use JsonStorage - we get these ten books (you can try home)

There is some new stuff

#04.4 - Instad of reusing the previous model and adding manually new properties let's copy the data in json and

make space under the BookModel class and put cursor there

Alt text

then PasteSpecial JSON as Classes

Alt text

#04.5 Now we have to adjust a bit an auto-generated code - we can just delete this part (Mind brackts!)

Alt text

#04.6 Properties should start with capital letters

Alt text

#04.7 And as we remember "Id" sould be long

result

namespace AbcItWebApi.Models
{
            public class BookModel
    {
            public long Id { get; set; }
            public string Name { get; set; }
            public string Author { get; set; }
            public string Genre { get; set; }
            public string Price { get; set; }
            public string ImgUrl { get; set; }
            public string Url { get; set; }
            public string BackgroundColor { get; set; }
            public string TextColor { get; set; }
            public string About { get; set; }
    }
}

#05 Now let's go back to Controller

#05.1 Instead of returning strings we want to return books

(Don't vaste time filling "real" data but still write something you can see the result is OK)

        [HttpGet(Name = "GetMyLibrary")]
            public IEnumerable<BookModel> Get()
        {
            return [new BookModel {
                About = "About Value",
                Author = "Author Value",
                BackgroundColor = "Backround color value",
                Genre = "Genre value",
                Id = 0,
                ImgUrl = "Img url value",
                Name = "Name value",
                Price = "Price value",
                TextColor = "Text color value",
                Url = "Url value"
            }];
        }

#05.2 Run and test the API

Still working? Great.

We are not done yet with Controller obviously - but let's focus now on the FE for a while

#05 Create wwwroot folder (it must be named exactly wwwroot)

Alt text

#06 Add some pre-prepered (FE workshop created) pages

#07 Adjust the Project class

Alt text

app.UseStaticFiles();

_(Test the app now calling the url of the new added file(s))

Now back to Controller

#08 Udjest the Get method (add some mock data) + create a new Detail method

using AbcItWebApi.Models;
using Microsoft.AspNetCore.Mvc;

namespace AbcItWebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
            public class MyLibraryController : ControllerBase
    {
            //private readonly ILogger<MyLibraryController> _logger;

            //public MyLibraryController(ILogger<MyLibraryController> logger)
            //{
            //    _logger = logger;
            //}

            readonly List<BookModel> books =
            [
            new BookModel
                {
                    Id = 1,
                    Name = "Harry Potter and the Order of the Phoenix",
                    Author = "J. K. Rowling",
                    Genre = "Fantasy novel",
                    Price = "€13.70",
                    ImgUrl = "images/1.jpg",
                    Url = "https://www.amazon.com/Harry-Potter-Order-Phoenix-Book/dp/043935806X",
                    BackgroundColor = "#145E8C",
                    TextColor = "#C1E7FF",
                    About = "As his fifth year at Hogwarts School of Witchcraft and Wizardry approaches, 15-year-old Harry Potter is in full-blown adolescence, complete with regular outbursts of rage, a nearly debilitating crush, and the blooming of a powerful sense of rebellion. It's been yet another infuriating and boring summer with the despicable Dursleys, this time with minimal contact from our hero's non-Muggle friends from school. Harry is feeling especially edgy at the lack of news from the magic world, wondering when the freshly revived evil Lord Voldemort will strike. Returning to Hogwarts will be a relief... or will it?"
                },
            new BookModel
                {
                    Id = 2,
                    Name = "The Alchemist",
                    Author = "Paulo Coelho",
                    Genre = "Psychological novel",
                    Price = "€9.90",
                    ImgUrl = "images/2.jpg",
                    Url = "https://www.amazon.com/Alchemist-Paulo-Coelho/dp/0722532938/",
                    BackgroundColor = "#F5CC4D",
                    TextColor = "#6F5401",
                    About = "Like the one-time bestseller Jonathan Livingston Seagull, The Alchemist presents a simple fable, based on simple truths and places it in a highly unique situation. And though we may sniff a bestselling formula, it is certainly not a new one: even the ancient tribal storytellers knew that this is the most successful method of entertaining an audience while slipping in a lesson or two. Brazilian storyteller Paulo Coehlo introduces Santiago, an Andalusian shepherd boy who one night dreams of a distant treasure in the Egyptian pyramids. And so he's off: leaving Spain to literally follow his dream."
                },
            new BookModel
                {
                    Id = 3,
                    Name = "Killing Moon",
                    Author = "Jo Nesbo",
                    Genre = "Thriller",
                    Price = "€24.90",
                    ImgUrl = "images/3.jpg",
                    Url = "https://www.amazon.com/Killing-Moon/dp/1787303780",
                    BackgroundColor = "#005660",
                    TextColor = "#A9D9DF",
                    About = "This killer will get inside your head. Two young women are missing. Strangers to each other, but last seen at the same party. When the body of one of them is found with fresh stitches along her hairline the hunt is on to find a murderer with very particular tastes. Catching this criminal calls for a detective with a very particular mind."
                },
            new BookModel
                {
                    Id = 4,
                    Name = "The Library of Heartbeats",
                    Author = "Laura Imai Messina",
                    Genre = "Novel",
                    Price = "€13.10",
                    ImgUrl = "images/4.jpg",
                    Url = "https://www.amazon.com/Library-Heartbeats-heart-rending-Japanese-set-international-ebook/dp/B0C96FMRG3",
                    BackgroundColor = "#FBA5C8",
                    TextColor = "#87214A",
                    About = "To find what you have lost, you must listen to your heart . . . On the peaceful Japanese island of Teshima there is a library of heartbeats, a place where the heartbeats of visitors from all around the world are collected. In this small, isolated building, the heartbeats of people who are still alive or have already passed away continue to echo."
                },
            new BookModel
                {
                    Id = 5,
                    Name = "Red Side Story",
                    Author = "Jasper Fforde",
                    Genre = "Science fiction fantasy",
                    Price = "€19.40",
                    ImgUrl = "images/5.jpg",
                    Url = "https://www.amazon.com/Red-Side-Story-long-awaited-bestselling-ebook/dp/B09RPG3XMN",
                    BackgroundColor = "#E4CD00",
                    TextColor = "#615700",
                    About = "Imagine a world where your position in society depended on what bit of the colour spectrum you could see. This is the world inhabited by Eddie Russett (red, middle-level) and Jane Grey (monochromatic, lowest in society)."
                },
            new BookModel
                {
                    Id = 6,
                    Name = "Two Can Keep a Secret",
                    Author = "Karen M. McManus",
                    Genre = "Thriller",
                    Price = "€21.60",
                    ImgUrl = "images/6.jpg",
                    Url = "https://www.amazon.com/TWO-KEEP-SECRET-Karen-McManus/dp/0141375655",
                    BackgroundColor = "#4CA7A8",
                    TextColor = "#003638",
                    About = "Echo Ridge is small-town America. Ellery's never been there, but she's heard all about it. Her aunt went missing there at age seventeen. And only five years ago, a homecoming queen put the town on the map when she was killed."
                },new BookModel
                {
                    Id = 7,
                    Name = "The Hobbit",
                    Author = "J. R. R. Tolkien",
                    Genre = "Fantasy",
                    Price = "€9.20",
                    ImgUrl = "images/7.jpg",
                    Url = "https://www.amazon.com/Hobbit-J-R-R-Tolkien/dp/0618260307",
                    BackgroundColor = "#005931",
                    TextColor = "#9EDABF",
                    About = "'In a hole in the ground, there lived a hobbit.' So begins one of the most beloved and delightful tales in the English language. Set in the imaginary world of Middle-earth, at once a classic myth and a modern fairy tale, J.R.R. Tolkien's The Hobbit is one of literature's most enduring and well-loved novels. The text in this 372-page paperback edition is based on that first published in Great Britain by Collins Modern Classics and includes a note on the text by Douglas A. Anderson. Bilbo Baggins is a hobbit who enjoys a comfortable, unambitious life, rarely traveling any farther than his pantry or cellar. But his contentment is disturbed when the wizard Gandalf and a company of dwarves arrive on his doorstep one day to whisk him away on an adventure. They have launched a plot to raid the treasure hoard guarded by Smaug the Magnificent, a large and very dangerous dragon. Bilbo reluctantly joins their quest, unaware that on his journey to the Lonely Mountain he will encounter both a magic ring and a frightening creature known as Gollum."
                },
            new BookModel
                {
                    Id = 8,
                    Name = "The Subtle Art of Not Giving a F*ck",
                    Author = "Mark Manson",
                    Genre = "Self-help",
                    Price = "€17.60",
                    ImgUrl = "images/8.jpg",
                    Url = "https://www.amazon.com/Subtle-Art-Not-Giving-Counterintuitive/dp/0062641549",
                    BackgroundColor = "#231E20",
                    TextColor = "#96898E",
                    About = "For decades, we’ve been told that positive thinking is the key to a happy, rich life. 'F**k positivity,' Mark Manson says. 'Let’s be honest, shit is f**ked and we have to live with it.' In his wildly popular Internet blog, Manson doesn’t sugarcoat or equivocate. He tells it like it is—a dose of raw, refreshing, honest truth that is sorely lacking today. The Subtle Art of Not Giving a F**k is his antidote to the coddling, let’s-all-feel-good mindset that has infected modern society and spoiled a generation, rewarding them with gold medals just for showing up. Manson makes the argument, backed both by academic research and well-timed poop jokes, that improving our lives hinges not on our ability to turn lemons into lemonade, but on learning to stomach lemons better. Human beings are flawed and limited—'not everybody can be extraordinary, there are winners and losers in society, and some of it is not fair or your fault.' Manson advises us to get to know our limitations and accept them. Once we embrace our fears, faults, and uncertainties, once we stop running and avoiding and start confronting painful truths, we can begin to find the courage, perseverance, honesty, responsibility, curiosity, and forgiveness we seek."
                },
            new BookModel
                {
                    Id = 9,
                    Name = "House of Earth and Blood",
                    Author = "Sarah J. Maas",
                    Genre = "Science fiction fantasy",
                    Price = "€25.50",
                    ImgUrl = "images/9.jpg",
                    Url = "https://www.amazon.com/House-Earth-Blood-Crescent-City/dp/1635574048",
                    BackgroundColor = "#8D2D26",
                    TextColor = "#FFD1CE",
                    About = "Bryce Quinlan had the perfect life-working hard all day and partying all night-until a demon murdered her closest friends, leaving her bereft, wounded, and alone. When the accused is behind bars but the crimes start up again, Bryce finds herself at the heart of the investigation. She'll do whatever it takes to avenge their deaths. Hunt Athalar is a notorious Fallen angel, now enslaved to the Archangels he once attempted to overthrow. His brutal skills and incredible strength have been set to one purpose-to assassinate his boss's enemies, no questions asked. But with a demon wreaking havoc in the city, he's offered an irresistible deal: help Bryce find the murderer, and his freedom will be within reach. As Bryce and Hunt dig deep into Crescent City's underbelly, they discover a dark power that threatens everything and everyone they hold dear, and they find, in each other, a blazing passion-one that could set them both free, if they'd only let it. With unforgettable characters, sizzling romance, and page-turning suspense, this richly inventive new fantasy series by #1 New York Times bestselling author Sarah J. Maas delves into the heartache of loss, the price of freedom-and the power of love."
                },
            new BookModel
                {
                    Id = 10,
                    Name = "It",
                    Author = "Stephen King",
                    Genre = "Horror novel",
                    Price = "€19.60",
                    ImgUrl = "images/10.jpg",
                    Url = "https://www.amazon.com/King-Stephen/dp/1444707868",
                    BackgroundColor = "#20381E",
                    TextColor = "#AFB5AE",
                    About = "Derry, Maine is just an ordinary town: familiar, well-ordered for the most part, a good place to live. It is a group of children who see - and feel - what makes Derry so horribly different. In the storm drains, in the sewers, IT lurks, taking on the shape of every nightmare, each one's deepest dread. Sometimes is appears as an evil clown named Pennywise and sometimes IT reaches up, seizing, tearing, killing... Time passes and the children grow up, move away and forget. Until they are called back, once more to confront IT as IT stirs and coils in the sullen depths of their memories, emerging again to make their past nightmares a terrible present reality."
                }
            ];

        [HttpGet("{id}", Name = "GetBookDetail")]
            public BookModel GetBook(long id)
        {
            return books.FirstOrDefault(book => book.Id == id) ?? new BookModel();
        }

        [HttpGet(Name = "GetMyLibrary")]
            public IEnumerable<BookModel> Get()
        {
            return books;
        }
    }
}

Test app now again

Now we replace the mock data with real db data

#09 Create a new folder Data

Alt text

#10 Now you can create a table and populate it with data 😋 or copy-paste the pre-prepared db

Alt text

#11 Create Storage folder and DbStorage.cs inside it.

Alt text

#12 Now we just reuse our old implementation - just a bit adjusted

using AbcItWebApi.Models;
using Microsoft.Data.Sqlite;

namespace AbcItWebApi.Storage
{
            public class DbStorage
    {
            private readonly string connectionString;
            public DbStorage()
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string dbPath = Path.Combine(baseDirectory, "Data", "MyLibrary.db");
            //const string dbPath = @"C:\Users\ivan.korecek\source\repos\AbcItWebApi\Data\MyLibrary.db";
            connectionString = $@"Data Source={dbPath};";
        }

            public List<BookModel> LoadBooks()
        {
            var result = new List<BookModel>();
            try
            {
            using (var connection = new SqliteConnection(connectionString))
                {
                    connection.Open();
            var command = new SqliteCommand("SELECT id, Name, Author, Genre, Price, ImgUrl, Url, BackgroundColor, TextColor, About FROM MyLibrary", connection);

            using (var reader = command.ExecuteReader())
                    {
            while (reader.Read())
                        {
            var id = (long)reader["id"];
            var name = reader["Name"].ToString();
            var author = reader["Author"].ToString();
            var genre = reader["Genre"].ToString();
            var price = reader["Price"].ToString();
            var imgUrl = reader["ImgUrl"].ToString();
            var url = reader["Url"].ToString();
            var backgroundColor = reader["BackgroundColor"].ToString();
            var textColor = reader["TextColor"].ToString();
            var about = reader["About"].ToString();

                            result.Add(
            new BookModel
                                {
                                    Id = id,
                                    Name = name,
                                    Author = author,
                                    Genre = genre,
                                    Price = price,
                                    ImgUrl = imgUrl,
                                    Url = url,
                                    BackgroundColor = backgroundColor,
                                    TextColor = textColor,
                                    About = about
                                });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return result;
        }

            public void SaveBooks(List<BookModel> books)
        {
            try
            {
            using (var connection = new SqliteConnection(connectionString))
                {
                    connection.Open();
            var query = "INSERT INTO MyLibrary (Name, Author, Genre, Price, ImgUrl, Url, BackgroundColor, TextColor, About) VALUES (@Name, @Author, @Genre, @Price, @ImgUrl, @Url, @BackgroundColor, @TextColor, @About)";
            foreach (var book in books)
                    {
            if (book.Id != 0)
                        {
            continue;
                        }

            using (var command = new SqliteCommand(query, connection))
                        {
            // Use parameters to prevent SQL injection
                            command.Parameters.AddWithValue("@Name", book.Name);
                            command.Parameters.AddWithValue("@Author", book.Author);
                            command.Parameters.AddWithValue("@Genre", book.Genre);
                            command.Parameters.AddWithValue("@Price", book.Price);
                            command.Parameters.AddWithValue("@ImgUrl", book.Price);
                            command.Parameters.AddWithValue("@Url", book.Price);
                            command.Parameters.AddWithValue("@BackgroundColor", book.Price);
                            command.Parameters.AddWithValue("@TextColor", book.Price);
                            command.Parameters.AddWithValue("@About", book.About);

            // Execute the command
                            command.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

#13 SQLite package is missing

Alt text

#14 (For .Net Core 8.0) we have to add one more package: SQLitePCLRaw.bundle_e_sqlite3

#15 Then we have to add this piece of code to Program.cs

Alt text

SQLitePCL.Batteries.Init();

Now we have basic fully functional implementation of web page. Any changes in db will reflect on MyLibrary page.