.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

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. Liberty is a Senior AI Engineer at the University of Pittsburgh Medical Center, and 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 21 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. I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 positive. Any suggestions or advice would be greatly appreciated. Thank you

  2. Timsothybioli's avatar Timsothybioli says:

    Keep this going please, great job!
    https://share.google/PHAZkP9vf1T4WzAIj

  3. LewisGor's avatar LewisGor says:

    What’s up, after reading this awesome paragraph i am too cheerful to share my knowledge here with friends.
    https://stork.kiev.ua/yak-rozibraty-faru-za-tsinoyu-chashky-kavy-1.html

  4. tvbet's avatar tvbet says:

    Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any tips and hints for novice blog writers? I’d genuinely appreciate it.

  5. aajogo's avatar aajogo says:

    magnificent publish, very informative. I wonder why the opposite specialists of this sector don’t realize this. You must proceed your writing. I’m sure, you have a huge readers’ base already!

  6. ph888's avatar ph888 says:

    Hello, after reading this amazing piece of writing i am as well happy to share my know-how here with friends.

  7. Stephenviaps's avatar Stephenviaps says:

    What’s up, I want to subscribe for this blog to obtain hottest updates, thus where can i do it please help out.
    https://drive.google.com/file/d/1qFVvsmTNDQ4CPDO-WTyXS97GppJt7Ix-/view?usp=sharing

  8. Timsothybioli's avatar Timsothybioli says:

    This is really interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your wonderful post. Also, I’ve shared your site in my social networks!
    https://share.google/94lMYMJ8DKRmvwrqW

  9. Stephenviaps's avatar Stephenviaps says:

    This is the right blog for everyone who would like to find out about this topic. You know so much its almost tough to argue with you (not that I really will need to…HaHa). You certainly put a brand new spin on a subject that has been discussed for a long time. Excellent stuff, just wonderful!
    https://share.google/VZDoImO4q7IN57W0l

  10. LewisGor's avatar LewisGor says:

    I used to be able to find good information from your articles.
    https://share.google/rAEmgS782KInPHj9U

  11. OLanepiliA's avatar OLanepiliA says:

    I believe what you composed was very reasonable. However, what about this? what if you added a little content? I am not suggesting your content is not good., but suppose you added a post title to possibly grab folk’s attention? I mean %BLOG_TITLE% is a little plain. You should glance at Yahoo’s front page and watch how they write news titles to grab viewers to open the links. You might add a video or a related picture or two to grab readers interested about everything’ve got to say. Just my opinion, it might make your posts a little bit more interesting.
    https://share.google/DAzGKt04pFPzLHnQG

  12. DichaelAlono's avatar DichaelAlono says:

    Do you have a spam problem on this site; I also am a blogger, and I was wondering your situation; many of us have created some nice procedures and we are looking to exchange strategies with others, be sure to shoot me an email if interested.
    https://share.google/qjVCzg079LspjKvX0

  13. Fobertnap's avatar Fobertnap says:

    Why visitors still use to read news papers when in this technological world all is available on web?
    https://share.google/4ayG8YVlseDoPFRol

  14. GichardAmomi's avatar GichardAmomi says:

    Hey I am so happy I found your web site, I really found you by accident, while I was researching on Yahoo for something else, Anyhow I am here now and would just like to say cheers for a marvelous post and a all round interesting blog (I also love the theme/design), I don’t have time to look over it all at the minute but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.
    https://share.google/s5sPyIskZBsxIBZst

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

    В каких ситуациях необходим Мастер на час?

    Спектр задач очень обширен. Назову только самых частых:

    Мелкий бытовой ремонт. Когда внезапно расшаталась дверная ручка. Мастер на час в срочном порядке появится и исправит проблему.
    Монтаж и подключение предметов интерьера. Требуется установить новый шкаф? Не стоит действовать наугад. Квалифицированный мастер сделает все аккуратно и правильно.
    Услуги по креплению габаритных вещей. Закрепить картину крепко и безопасно — это работа для Мастер на час.
    Экстренные ремонтные работы. Засор в раковине? Компетентный работник имеет инструмент для решения проблемы.

    Основные плюсы обращения к профессионалу

    Почему именно такой выбор? Объясняю:

    1. Сохранение нервов. Вам не потребуется целый день на попытки решить. Мастер выполнит задачу значительно скорее.
    2. Качество и гарантия. Надежный специалист несет ответственность на выполненные услуги. Вы защищены.
    3. Правильные инструменты. Вам не придется покупать специальный ключ. У мастера все есть.
    4. Отсутствие рисков. Сантехника, проводка, газ — это не место для кустарных методов. Поручите задачу экспертам.

    Таким образом хочу отметить: услуга Муж на час в Москве — это не причуда, а современный подход для активного жителя мегаполиса, который ценит свое время. Рекомендую прибегнуть к такой услугой.
    Почему выбрать Муж на час Москва?
    Разнообразный ассортимент услуг: с сантехники.

    Выезд по Москве к МКАД с выездом вне МКАД.

    Тарифы конкурентные – лишь 1500 руб за работу.

    Гарантия для ремонт от 1 дня.

    24/7 работа.

    Какими услуги предлагает Муж на час?
    Сантехника: Замена кранов; устранение засоров.

    Электрика: Установка щитков; осмотр поломок.

    Мебель и дом: Сборка столов.

    Двери и механизмы: Регулировка замков.

    Другое: Установка кондиционеров.

    Свяжитесь оперативно! Номер. Штаб – везде. Мастер на час – лучший спасатель при срочно.

    Обратитесь специалистам Муж на час Москва в час. Исполнение проверено тысячами жителей.

  16. В нашем ассортименте представлены и классические, и современные варианты ковров для любого интерьера.
    Лучшие шерстяные ковры
    Заказы мы доставляем оперативно и с заботой по Краснодару и ближним областям.

  17. Jamesbobby's avatar Jamesbobby says:

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

  18. hi88's avatar hi88 says:

    An impressive share! I have just forwarded this onto a friend who was doing a little research on this. And he in fact bought me lunch because I discovered it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanks for spending time to discuss this matter here on your web page.

  19. Мастер на час – это профессиональная услуга для исправления бытовых дефектов в столице России. Когда поломался кран, никак имеет смысл искать недели. Сертифицированные ремонтники подъедут срочно по всему городу.

    Для чего выбрать Муж на час в Москве?
    Широкий спектр услуг: с сборки мебели.

    Выезд по Москве в МКАД и за МКАД.

    Тарифы выгодные – минимум 1500 руб за работу.

    Обязательство на результат до 1 недели.

    Нон-стоп доступность.

    Перечень ремонт предлагает Мастер на час?
    Сантехника: Замена труб; исправление утечек.

    Электрика: Монтаж щитков; анализ обрывов.

    Мебель и дом: Ремонт картин.

    Двери и ручки: Взлом порогов.

    Другое: Монтаж стиральных машин.

    Пишите немедленно! Контакт. Штаб – центр. Муж на час в Москве – профессиональный герой на быстро.

    Используйте специалистам Муж на час в Москве по столице. Работа проверено более 5000 жителей.

  20. DichaelAlono's avatar DichaelAlono says:

    Hello to every one, the contents existing at this website are really amazing for people experience, well, keep up the good work fellows.
    https://slovakia.kiev.ua/okupnist-instrumentu-yak-ultrazvukovyi-nizh.html

  21. Timsothybioli's avatar Timsothybioli says:

    It’s remarkable to visit this web page and reading the views of all mates concerning this article, while I am also keen of getting familiarity.
    https://jesus.com.ua/trishchyny-na-bachku-omyvacha-chy.html

  22. hi88's avatar hi88 says:

    Very good post. I will be going through some of these issues as well..

  23. Simple yet informative. This post is better than many I鈥檝e seen elsewhere.

  24. winpot's avatar winpot says:

    I’m curious to find out what blog system you happen to be working with? I’m experiencing some small security problems with my latest blog and I’d like to find something more risk-free. Do you have any recommendations?

  25. Lonnie's avatar Lonnie says:

    เนื้อหานี้ น่าสนใจดี ค่ะ
    ดิฉัน ได้อ่านบทความที่เกี่ยวข้องกับ
    เรื่องที่เกี่ยวข้อง
    ดูต่อได้ที่ Lonnie
    เผื่อใครสนใจ
    มีการยกตัวอย่างที่เข้าใจง่าย
    ขอบคุณที่แชร์ บทความคุณภาพ นี้
    และอยากเห็นบทความดีๆ แบบนี้อีก

  26. 日本 av's avatar 日本 av says:

    It’s a shame you don’t have a donate button! I’d certainly donate to this superb blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this website with my Facebook group. Chat soon!

  27. BobbyTUT's avatar BobbyTUT says:

    Я смог найти полезную информацию в ваших постах.
    р7 официальный сайт

  28. LewisGor's avatar LewisGor says:

    Hi to all, how is the whole thing, I think every one is getting more from this web site, and your views are fastidious in favor of new viewers.
    https://screensflare.com/cats-types—benefits-and-disadvantages-4128590151772491621

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

    Муж на час в Москве: Ключевые направления работ
    Мелкий ремонт: Муж на час оперативно устранит Муж на час в Москве протечку крана, установит смеситель, соберет мебель или Мастер на час починит дверную ручку.
    Электромонтажные услуги: Грамотный Муж на час Москва безопасно заменит розетку, выключатель, Муж на час смонтирует светильник или подключит бытовую технику.
    Сантехнические работы: Вызов Мастер на час — это замена шлангов, устранение засоров, Муж на час в Москве монтаж полотенцесушителя или установка унитаза.
    Помощь с монтажом: Надежный Муж на час в Москве повесит тяжелые Мастер на час зеркала, картины, карнизы, Муж на час соберет детский спортивный комплекс или установит технику.

    Муж на час Москва: Преимущества профессионального подхода
    Обращаясь к проверенному Муж на час, вы получаете не просто физическую помощь, а комплекс преимуществ:
    1. Экономия времени: Квалифицированный Муж на час в Москве выполнит задачу в разы быстрее.
    2. Качество и гарантия: Опытный Мастер на час Москва дает гарантию на свои работы.
    3. Решение «под ключ»: Хороший Мастер на час приедет со своим инструментом и материалами.
    4. Безопасность: Профессиональный Муж на час Москва соблюдает технику безопасности.

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

  30. GichardAmomi's avatar GichardAmomi says:

    This is really interesting, You’re a very professional blogger. I’ve joined your feed and sit up for looking for more of your excellent post. Also, I’ve shared your website in my social networks
    https://share.google/kR5KKMWqJGPUBqKCN

  31. OLanepiliA's avatar OLanepiliA says:

    Explore detailed insights on ihome color changing wh alarm clocks at TOPCLOCKS, including features, comparisons, and expert recommendations for smarter buying decisions.

  32. LeroyHom's avatar LeroyHom says:

    Эта статья погружает вас в увлекательный мир знаний, где каждый факт становится открытием. Мы расскажем о ключевых исторических поворотных моментах и научных прорывах, которые изменили ход цивилизации. Поймите, как прошлое формирует настоящее и как его уроки могут помочь нам строить будущее.
    Где можно узнать подробнее? – http://www.attitudereality.com/2025/10/calm-by-design-building-small-systems-that-tame-big-stress

  33. DavidVof's avatar DavidVof says:

    Фантастически, какой сайт! Этот блог предоставляет полезные факты, продолжайте в том же духе!
    https://your-yoga.ru/?p=1

  34. Scottgealp's avatar Scottgealp says:

    Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
    Углубиться в тему – https://voertuigtaxatiecertificaat.nl/hello-world

  35. Edwardcop's avatar Edwardcop says:

    Вау, восхитительный дизайн блога! Как долго вы ведёте блог? Вы делаете это легко! Весь внешний вид сайта — великолепный, не говоря уже о контенте!
    https://kick-box.ru/indeks-cen-na-gruzovye-zapchasti-2026-statistika-rosta-po-agregatam-i-prognoz/

  36. IsmaelNiz's avatar IsmaelNiz says:

    Hi there colleagues, how is the whole thing, and what you would like to say on the topic of this paragraph, in my view its in fact amazing in support of me.
    byueuropaviagraonline

  37. Leonelcot's avatar Leonelcot says:

    В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
    Уточнить детали – https://publixadweeklyad.com/publix-gift-cards

  38. 真实的人类第三季高清完整版,海外华人可免费观看最新热播剧集。

  39. LhanepiliA's avatar LhanepiliA says:

    What’s up everybody, here every person is sharing these kinds of knowledge, therefore it’s fastidious to read this webpage, and I used to visit this blog all the time.
    byueuropaviagraonline

  40. Timsothybioli's avatar Timsothybioli says:

    It’s amazing designed for me to have a site, which is valuable in favor of my know-how. thanks admin
    byueuropaviagraonline

  41. serviceMuh's avatar serviceMuh says:

    Решение есть, на этом форуме ее обсуждали и поделились ссылкой на тех, кто ее решил

  42. serviceMuh's avatar serviceMuh says:

    Почему Ваше устройство не работает? Прочитай перед походом в сервисный центр советы мастеров и может быть ремонт совсем не потребуется

  43. Timsothybioli's avatar Timsothybioli says:

    For newest news you have to go to see web and on internet I found this web page as a most excellent website for most up-to-date updates.
    https://share.google/dhKRPMWsiQyOclwYP

  44. Timsothybioli's avatar Timsothybioli says:

    whoah this weblog is great i like reading your posts. Keep up the good work! You recognize, a lot of individuals are searching round for this information, you can help them greatly.
    byueuropaviagraonline

  45. OLanepiliA's avatar OLanepiliA says:

    Hi to all, how is everything, I think every one is getting more from this web site, and your views are nice designed for new people.
    byueuropaviagraonline

  46. onlinecasino's avatar onlinecasino says:

    FIFA Club World Cup livescore, continental champions competing for global title

  47. IsmaelNiz's avatar IsmaelNiz says:

    Hi colleagues, pleasant paragraph and nice urging commented at this place, I am truly enjoying by these.
    byueuropaviagraonline

  48. Bryandrort's avatar Bryandrort says:

    дорогие проститутки уфы проститутки город уфа

  49. IsmaelNiz's avatar IsmaelNiz says:

    Hi there, its nice post on the topic of media print, we all know media is a wonderful source of facts.
    byueuropaviagraonline

Comments are closed.