.NET APIs Part 5 – All the CRUD APIs

In the previous posting we saw how to create an API to get all the cars in our database. In this posting we’ll look at the remaining CRUD (Create Review Update Delete) operations.

As you may remember, we created a controller named CarController. ASP.NET will strip off the word Controller, leaving us with Car, which we will use to access the endpoints of our API.

An endpoint is just a URL that takes us to the operation we want.

We looked at GetAll, let’s take a look at Get. In this case, we have an id for the car we want, but we want all the details of that car. Simple!

First we need a method in our controller:

[HttpGet("{id}")]
public async Task<ActionResult<Car>> Get(int id)
{
   var car = await _carRepository.Get(id);
   if (car == null)
   {
      return NotFound();
   }
   return car;
}


Notice that next to the HttpGet attribute we indicate that the endpoint will take the id of the car we want

[HttpGet("{id}")]

This means we need to modify the URL to access the endpoint by adding the actual id of the desired record.

The first thing we do is call the repository, passing in the id.

public async Task<Car?> Get(int id)
{
   var query = "select * from car where id=@id";
   using var db = databaseConnectionFactory.GetConnection();
   return await db.QuerySingleOrDefaultAsync<Car>(query, new {id});
}

In the Get method of the repo we create our query, get our connection and execute the query returning the value we retrieved (if any). This is very close to what we did previously.

Back in the controller, we check to ensure that we received a Car. If not, we return NotFound which is a shorthand way of returning a 404 message. Otherwise we return the Car as a Json object. You can see this in Postman:

We’ll issue a Get command passing in the URL, ending with the id of the car we want (in this case 4)

 

 

 

Notice that we get back a 200, indicating success. In the body of the returned Json we get back all the details of the Car. (If you decide to use DTOs you can get whatever subset of the information makes sense):

{
    “id”: 4,
    “name”: “subaru impreza”,
    “mpg”: “16”,
    “cylinders”: “8”,
    “displacement”: “304”,
    “horsepower”: “150”,
    “weight”: “3433”,
    “acceleration”: “12”,
    “model_year”: “22”,
    “origin”: “usa”,
    “is_deleted”: “0”
}

Post

Adding a Car to the database is quite similar. We need a method in the controller and one in the repo. Here is the controller method:

[HttpPost]
public async Task<ActionResult<Car>> Post([FromBody] Car car)
{
   try
   {
      car = await _carService.Insert(car);
   }
   catch (Exception e)
   {
      return BadRequest(e); 
   }

   return CreatedAtAction(nameof(Get), new { id = car.Id }, car);
}

Look at the attribute in the parameter ([FromBody]. This indicates to the API that the data needed to insert this Car will be in the body of the call. The alternative is FromQuery. You can, in fact, use both in one call.

Note: CreatedAction causes a return code of 201, which is what we want. Here’s the body we’ll insert:

{
        “name”: “chevrolet chevelle malibu”,
        “mpg”: “18”,
        “cylinders”: “8”,
        “displacement”: “307”,
        “horsepower”: “130”,
        “weight”: “3504”,
        “acceleration”: “12”,
        “model_year”: “70”,
        “origin”: “usa”,
        “is_deleted”: “0”
    }

When we click Send this data is sent to the API which returns 201 (created) and in the body of the returned data we see the new id assigned to this car

{
    “id”: 409,
    “name”: “chevrolet chevelle malibu”,
    “mpg”: “18”,
    “cylinders”: “8”,
    “displacement”: “307”,
    “horsepower”: “130”,
    “weight”: “3504”,
    “acceleration”: “12”,
    “model_year”: “70”,
    “origin”: “usa”,
    “is_deleted”: “0”
}

Service Class

Notice that this time, instead of calling the Repo directly, the method in the controller calls into a service class. A service class is a great way to get the logic out of the controller, where it does not belong, without putting it into the repo, where it also does not belong.

Here’s the top of the CarService

public class CarService : ICarService
{
   private readonly ICarRepository _carRepository;

   public CarService(ICarRepository carRepository)
   {
      _carRepository = carRepository;
   }

   public async Task<Car> Insert(Car car)
   {
      var newId = await _carRepository.UpsertAsync(car);
      if (newId > 0)
      {
         car.Id = newId;
      }
      else
      {
         throw new Exception("Failed to insert car");
      }
   return car;
   }

All the logic associated with this insert (e.g., making sure we get back a legitimate id from the repository, etc.) is encapsulated in the service.

This leaves the repository free to just talk to the database,

public async Task<int> UpsertAsync(Car car)
{
using var db = databaseConnectionFactory.GetConnection();
var sql = @"
DECLARE @InsertedRows AS TABLE (Id int);
MERGE INTO Car AS target
USING (SELECT @Id AS Id, @Name AS Name, @Model_Year AS Model_Year, 
@Is_Deleted AS Is_Deleted, @Origin AS origin ) AS source 
ON target.Id = source.Id
WHEN MATCHED THEN 
UPDATE SET 
Name = source.Name, 
Model_Year = source.Model_Year, 
Is_Deleted = source.Is_Deleted,
Origin = source.Origin
WHEN NOT MATCHED THEN
INSERT (Name, Model_Year, Is_Deleted, Origin)
VALUES (source.Name, source.Model_Year, 
source.Is_Deleted, source.Origin)
OUTPUT inserted.Id INTO @InsertedRows
;

SELECT Id FROM @InsertedRows;
";

var newId = await db.QuerySingleOrDefaultAsync<int>(sql, car);
return newId == 0 ? car.Id : newId;
}

Rather than having an insert and an update method, we combine that logic into this upsert method. This is a common idiom for database manipulation.

Note: to make this work, be sure to fill in all the fields for a car (or at least as many as you want to have in the Database.

Delete

As noted earlier, we will implement a soft delete; that is, rather than actually removing the data from the database, we’ll just set the is_deleted column to true. This allows us to reverse the action, and make the row not-deleted by simply changing that value to false.

[HttpDelete(“{id}”)]
public async Task<IActionResult> Delete(int id)
{
try
{
await _carService.Delete(id);
}
catch (Exception e)
{
return BadRequest(e);
}
return NoContent();
}

As you would expect, the endpoint takes an id (the id of the car we want to delete). The controller then hands that off to the service, which calls the repository which, in turn, marks that id as deleted:

public async Task<int> DeleteAsync(int id)
{
   using var db = databaseConnectionFactory.GetConnection();
   var query = "UPDATE car SET Is_Deleted = 1 WHERE Id = @Id";
   return await db.ExecuteAsync(query, new { Id = id });
}

If you are comfortable with SQL none of this will be very surprising. The key walkaway is:

Summary

In this post we saw that endpoints are just URLs with (potentially) data in the body of the request. The controller handles the URL and in our case passes the id or other data to the service. The service handles the (business) logic and then delegates talking to the database to the repository.

Book

This posting is excerpted from my forthcoming book Building APIs with .NET and C# to be released next year by Packt.

Unknown's avatar

About Jesse Liberty

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 13 year Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

2,765 Responses to .NET APIs Part 5 – All the CRUD APIs

  1. Bubblegum Gelato strain
    Thank you for sharing your knowledge, very precise information. Keep going!

  2. IsmaelNiz's avatar IsmaelNiz says:

    What’s up, this weekend is good in favor of me, since this occasion i am reading this impressive educational piece of writing here at my house.
    вход leebet

  3. GichardAmomi's avatar GichardAmomi says:

    Pretty! This was an incredibly wonderful article. Many thanks for providing these details.
    казино твин

  4. Timsothybioli's avatar Timsothybioli says:

    I relish, lead to I discovered exactly what I used to be taking a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye
    вход твин казино

  5. Stephenviaps's avatar Stephenviaps says:

    I was able to find good info from your blog articles.
    регистрация твин казино

  6. IsmaelNiz's avatar IsmaelNiz says:

    Hi there, all the time i used to check web site posts here in the early hours in the break of day, since i enjoy to learn more and more.
    официальный сайт lee bet

  7. IsmaelNiz's avatar IsmaelNiz says:

    Heya terrific website! Does running a blog similar to this require a lot of work? I’ve very little understanding of coding but I had been hoping to start my own blog in the near future. Anyways, should you have any suggestions or tips for new blog owners please share. I understand this is off subject but I just needed to ask. Appreciate it!
    https://art-svadba.ru/

  8. LhanepiliA's avatar LhanepiliA says:

    Just desire to say your article is as surprising. The clearness to your publish is just spectacular and i could suppose you are a professional on this subject. Fine along with your permission let me to grasp your RSS feed to keep up to date with approaching post. Thank you a million and please continue the enjoyable work.
    leebet casino

  9. Stephenviaps's avatar Stephenviaps says:

    Hello colleagues, how is all, and what you wish for to say regarding this piece of writing, in my view its actually awesome in support of me.
    https://withjim.in/sklo-dlya-far-vazhlivi-nyuansy-pry-vybori-ta-vstanovlenni

  10. WilliamHar's avatar WilliamHar says:

    Первое, что необходимо уточнить перед вызовом — наличие у врача лицензии и профильного медицинского образования. Только сертифицированный нарколог может назначить препараты, поставить капельницу и провести детоксикацию без ущерба для здоровья пациента.
    Ознакомиться с деталями – нарколог на дом анонимно в нижнем тагиле

  11. 390996 127138really good post, i surely enjoy this fabulous site, persist with it 234488

  12. OLanepiliA's avatar OLanepiliA says:

    you are in point of fact a good webmaster. The website loading velocity is incredible. It sort of feels that you are doing any distinctive trick. In addition, The contents are masterpiece. you’ve performed a great process on this topic!
    Car service near me

  13. IsmaelNiz's avatar IsmaelNiz says:

    Howdy exceptional website! Does running a blog like this take a great deal of work? I have no understanding of coding however I was hoping to start my own blog soon. Anyway, if you have any recommendations or techniques for new blog owners please share. I know this is off subject however I just had to ask. Thank you!
    Local limo company near me

  14. ShanepiliA's avatar ShanepiliA says:

    Hello colleagues, how is all, and what you would like to say concerning this piece of writing, in my view its in fact remarkable for me.
    Town car near me

  15. Bitzo's avatar Bitzo says:

    445513 883581Fascinating, but not ideal. Are you going to write far more? 256016

  16. OLanepiliA's avatar OLanepiliA says:

    Hi there everybody, here every one is sharing these know-how, thus it’s pleasant to read this website, and I used to pay a quick visit this webpage all the time.
    Car service near me

  17. EarnestCor's avatar EarnestCor says:

    Good day! This post could not be written any better! Reading this post reminds me of my previous room mate! He always kept chatting about this. I will forward this page to him. Fairly certain he will have a good read. Thank you for sharing!
    Town car near me

  18. 191595 696887I gotta bookmark this web site it seems very helpful very helpful 17836

  19. 952847 636128Extremely informative post. Your current Web site style is awesome as properly! 811767

  20. Davidobjen's avatar Davidobjen says:

    Мы оказываем услуги 24 часа в сутки, 7 дней в неделю, без выходных и праздников. Это позволяет:
    Получить больше информации – бесплатная наркологическая клиника

  21. IsmaelNiz's avatar IsmaelNiz says:

    Please let me know if you’re looking for a article author for your weblog. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d love to write some content for your blog in exchange for a link back to mine. Please blast me an email if interested. Many thanks!
    https://bookidoc.com.ua/korpus-fary-ta-vibratsiya-shcho-vplyvaye-na-d.html

  22. LhanepiliA's avatar LhanepiliA says:

    It’s remarkable in favor of me to have a web page, which is helpful for my know-how. thanks admin
    http://maranhaonegocios.com/porivnyannya-skla-riznykh-vyrobnykiv.html

  23. IsmaelNiz's avatar IsmaelNiz says:

    Why users still use to read news papers when in this technological globe the whole thing is presented on net?
    https://cancer.com.ua/pohodni-umovy-i-yakist-skla-eksperyment.html

  24. First Class Funk strain
    Very informative blog, highly recommended

  25. pg168's avatar pg168 says:

    291983 592085hello excellent web site i will definaely come back and see once again. 443050

  26. pg168's avatar pg168 says:

    524574 707339These kinds of Search marketing boxes normally realistic, healthy and balanced as a result receive just about every customer service necessary for some product. Link Building Services 813810

  27. Heya i am for the first time here. I found this board and
    I find It truly useful & it helped me out much. I hope to give something back and aid
    others like you helped me.

    Also visit my blog post gut drops reviews

  28. 842893 60130There is noticeably a bundle to know about this. I assume you created certain good points in functions also. 602848

  29. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  30. BlomblobSon's avatar BlomblobSon says:

    So, legend, I literally just ran into something shockingly creative, I had to pause my life and tell you.

    This thing is not your usual stuff. It’s packed with smooth UX, next-level thinking, and just the right amount of designer madness.

    Suspicious yet? Alright, witness the madness right on this link!

    You’re still here? Fine. Imagine a cat in a hoodie whipped up a site after reading memes. That’s the frequency this beast gives.

    So click already, and tattoo the link. Because real talk, this is worth it.

    Boom.

  31. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  32. Stephenviaps's avatar Stephenviaps says:

    What a stuff of un-ambiguity and preserveness of precious know-how regarding unpredicted emotions.
    https://3dlevsha.com.ua/vybir-linz-fari-styl-funktsional

  33. KelliDriep's avatar KelliDriep says:

    Этот информативный материал предлагает содержательную информацию по множеству задач и вопросов. Мы призываем вас исследовать различные идеи и факты, обобщая их для более глубокого понимания. Наша цель — сделать обучение доступным и увлекательным.
    Ознакомиться с деталями – https://www.hotel-sugano.com/bbs/sugano.cgi/datasphere.ru/club/user/12/blog/2477/www.skitour.su/sinopipefittings.com/e_Feedback/www.tovery.net/www.hip-hop.ru/forum/id298234-worksale/www.hip-hop.ru/sugano.cgi?page0=val

  34. StephantuB's avatar StephantuB says:

    Таблица 1: Основные признаки профессионального наркологического центра в Туле
    Разобраться лучше – http://narkologicheskaya-klinika-tula10.ru/chastnaya-narkologicheskaya-klinika-tula/

  35. StephantuB's avatar StephantuB says:

    Возможные признаки
    Подробнее тут – narkologicheskaya-klinika-tula10.ru/

  36. pg168's avatar pg168 says:

    138892 253408Greetings! This really is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading by way of your blog posts. Can you recommend any other blogs/websites/forums that deal with the same topics? Thank you so considerably! 141361

  37. StephantuB's avatar StephantuB says:

    Возможные признаки
    Подробнее тут – частная наркологическая клиника

  38. StephantuB's avatar StephantuB says:

    Показатель
    Получить дополнительные сведения – платная наркологическая клиника

  39. Nancyunfal's avatar Nancyunfal says:

    Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
    Разобраться лучше – http://capmeroccitanie.fr/sete-mysterieuse-enseigne-quai-dalger

  40. LindaShulk's avatar LindaShulk says:

    Медицинская публикация представляет собой свод актуальных исследований, экспертных мнений и новейших достижений в сфере здравоохранения. Здесь вы найдете информацию о новых методах лечения, прорывных технологиях и их практическом применении. Мы стремимся сделать актуальные медицинские исследования доступными и понятными для широкой аудитории.
    Разобраться лучше – нарколог на дом анонимно

  41. Apple Fritter
    You’ve built such a meaningful space for readers to learn, reflect, and feel inspired. Nice one!

  42. 714993 340549I got what you intend,bookmarked , extremely decent internet internet site . 958265

  43. Lindawex's avatar Lindawex says:

    В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
    Ознакомиться с деталями – https://faster-retail.com/it/reset-the-way-you-think-about-design-so-you-can-reach-new-heights-and-be-very-well

  44. EarnestCor's avatar EarnestCor says:

    Hey just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.
    cialis 5 mg prezzo in farmacia con ricetta

  45. I think the admin of this web site is actually working hard
    in support of his website, for the reason that here every information is quality based information.

    My website … MOUNFIT DROPS

  46. I just like the helpful info you supply to your articles.
    I will bookmark your blog and take a look at once more here regularly.
    I’m slightly sure I will learn lots of new stuff right right
    here! Good luck for the next!

    my web-site … hepatoburn review

  47. 766477 629743U never get what u expect u only get what u inspect 961574

  48. LewisGor's avatar LewisGor says:

    you are truly a good webmaster. The website loading speed is amazing. It kind of feels that you’re doing any distinctive trick. Also, The contents are masterpiece. you have done a fantastic activity on this subject!
    tadalafil teva 5 mg 28 compresse prezzo

  49. Fobertnap's avatar Fobertnap says:

    This site offers users a fast, efficient method to translate their PNG images into versatile SVG files. Using advanced vectorization algorithms, the tool ensures lines and shapes are accurately traced from pixel data. Creative professionals and marketers benefit from easy-to-edit SVGs ready for use in design software. With PNGTOSVGHero.com, you’ll enhance your image workflows and produce reliable vector assets on demand.
    PNG to SVG Converter

  50. LewisGor's avatar LewisGor says:

    The Dominican Republic is a sunny place, but it’s worth knowing about hurricane season. Typically it covers the period from early June to November 30th, with peak activity in August and September .
    Despite the possibility of a direct hit from a tropical cyclone is relatively low, even indirect impact can cause downpours, flooding and strong winds. In this regard it’s advisable to stay informed about meteorological reports and possess an emergency action plan .
    If you’re planning a trip to the Dominican Republic during this period , think about obtaining travel insurance that includes flight cancellations or force majeure circumstances related to weather. Be aware of the possibility of short-term interruptions in logistics and recreation. Your safety is paramount.
    dom rep hurricane season

Leave a Reply

Your email address will not be published. Required fields are marked *