.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. RobertMen's avatar RobertMen says:

    https://easyindiameds.com/# п»їlegitimate online pharmacies india

  2. GeraldoTup's avatar GeraldoTup says:

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

  3. Williamsap's avatar Williamsap says:

    bahiscasino casino bahiscasino resmi

  4. IsmaelNiz's avatar IsmaelNiz says:

    This is really interesting, You’re an excessively skilled blogger. I have joined your feed and look forward to in quest of extra of your wonderful post. Also, I have shared your web site in my social networks
    buy cannabis online for xxx adult porn video

  5. Bernardlen's avatar Bernardlen says:

    В рамках работы клиники проводятся диагностические процедуры и различные виды терапии, включающие:
    Исследовать вопрос подробнее – платная наркологическая клиника

  6. Scottdat's avatar Scottdat says:

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

  7. Jamesmot's avatar Jamesmot says:

    https://cialis.sbs/# Buy Tadalafil 20mg

  8. Jasonsoorb's avatar Jasonsoorb says:

    Лечение алкоголизма в Сергиевом Посаде важно рассматривать не как разовую «чистку» или временный перерыв, а как последовательный маршрут. Самый уязвимый период — первые 24–72 часа после прекращения употребления: днём может стать легче, но к вечеру и ночью волной возвращаются тревога и бессонница, усиливается внутреннее напряжение, появляются телесные симптомы. В этот момент человек чаще всего срывается, потому что ему кажется, что «иначе не выдержу». Поэтому качественная помощь строится так, чтобы пациент прошёл вечер и ночь безопасно, с понятными ориентирами и медицинской поддержкой, а затем перешёл к восстановлению и профилактике рецидива.
    Подробнее можно узнать тут – лечение алкоголизма цена

  9. spinbet's avatar spinbet says:

    Magnificent goods from you, man. I’ve understand your stuff previous to and you are just extremely fantastic. I really like what you’ve acquired here, really like what you are saying and the way in which you say it. You make it entertaining and you still take care of to keep it wise. I can’t wait to read far more from you. This is really a great site.

  10. Albertovergo's avatar Albertovergo says:

    Реабилитация алкоголиков в Москве с комплексным подходом — это многогранный процесс, включающий в себя не только медицинские процедуры, но и психологическую поддержку, физическую реабилитацию и помощь в социальной адаптации. Профессиональный реабилитационный центр обеспечивает индивидуальный подход к каждому пациенту, включая такие методы, как кодирование и своевременное лечение запоя. Важно отметить, что успешное лечение алкоголизма требует учета множества факторов, таких как степень зависимости, психоэмоциональное состояние пациента, а также его физическое здоровье. Комплексный подход помогает эффективно устранить все составляющие проблемы, минимизируя риски рецидивов.
    Подробнее можно узнать тут – reabilitacziya-alkogolikov-moskva-2.ru/

  11. 999jili's avatar 999jili says:

    Thank you for sharing your info. I truly appreciate your efforts and I will be waiting for your next post thank you once again.

  12. Ionencrive's avatar Ionencrive says:

    Thank you, I’ve recently been looking for information about this topic for a while and yours is the greatest I have came upon so far. However, what concerning the bottom line? Are you sure in regards to the source?
    tada-gaming.mobi

  13. melbet's avatar melbet says:

    Hi there, I enjoy reading all of your post. I like to write a little comment to support you.

  14. Henryplasy's avatar Henryplasy says:

    viagra canada Buy generic 100mg Viagra online buy Viagra over the counter

  15. Robertmaype's avatar Robertmaype says:

    Sildenafil Citrate Tablets 100mg order viagra Generic Viagra for sale

  16. Sharnecrive's avatar Sharnecrive says:

    Hi there friends, how is all, and what you would like to say on the topic of this paragraph, in my view its genuinely remarkable designed for me.
    Sweet Bonanza

  17. ivy casino's avatar ivy casino says:

    You actually make it appear really easy together with your presentation but I in finding this topic to be actually one thing that I believe I might never understand. It sort of feels too complex and very large for me. I am having a look ahead in your subsequent publish, I will attempt to get the hang of it!

  18. slotvip's avatar slotvip says:

    I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back later. All the best

  19. Sichestcrive's avatar Sichestcrive says:

    This info is invaluable. When can I find out more?
    Wolf Gold

  20. JessePiert's avatar JessePiert says:

    Реабилитация алкоголиков — это важный этап на пути к избавлению от зависимости. В Москве существует множество центров, предлагающих реабилитацию с индивидуальной программой, что помогает обеспечить более персонализированный и эффективный подход к каждому пациенту. Индивидуальная программа учитывает физическое и психологическое состояние человека, а также его социальное окружение и личные особенности. Это позволяет добиться лучших результатов в лечении и восстановлении.
    Выяснить больше – http://www.domen.ru

  21. mwplay888's avatar mwplay888 says:

    Hello there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thanks!

  22. 66win's avatar 66win says:

    Good day! I know this is kind of off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

  23. Appreciating the hard work you put into your site and detailed information you present. It’s great to come across a blog every once in a while that isn’t the same unwanted rehashed information. Fantastic read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  24. 747 live's avatar 747 live says:

    whoah this weblog is wonderful i really like studying your posts. Keep up the great work! You recognize, lots of people are looking round for this info, you can aid them greatly.

  25. coolbet's avatar coolbet says:

    You can definitely see your skills in the article you write. The world hopes for more passionate writers such as you who aren’t afraid to say how they believe. Always follow your heart.

  26. Aobiscrive's avatar Aobiscrive says:

    This web site really has all the information I needed concerning this subject and didn’t know who to ask.
    The Dog House Megaways

  27. ivy casino's avatar ivy casino says:

    I blog often and I truly thank you for your content. Your article has really peaked my interest. I’m going to bookmark your site and keep checking for new details about once a week. I opted in for your RSS feed too.

  28. Nelsontug's avatar Nelsontug says:

    Наиболее частыми причинами обращения становятся запой, выраженная слабость, тремор, тревога, бессонница, тошнота, нестабильное давление, учащенный пульс и ощущение физического истощения. Эти проявления могут сочетаться между собой и усиливаться после прекращения употребления алкоголя, особенно если эпизод длился несколько дней подряд.
    Подробнее тут – narkolog-na-dom-moskva-20.ru/

  29. EarnestCor's avatar EarnestCor says:

    Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m absolutely enjoying your blog and look forward to new updates.
    tada gaming slots

  30. My spouse and I stumbled over here coming from a different web address and thought I may as well check things out. I like what I see so now i’m following you. Look forward to checking out your web page for a second time.

  31. codere's avatar codere says:

    I am genuinely glad to read this web site posts which contains plenty of useful facts, thanks for providing these information.

  32. Good day! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

  33. Michaelkeymn's avatar Michaelkeymn says:

    Vet Pharm First pet meds official website Vet Pharm First

  34. fc178's avatar fc178 says:

    Having read this I thought it was rather enlightening. I appreciate you spending some time and effort to put this article together. I once again find myself spending a significant amount of time both reading and posting comments. But so what, it was still worthwhile!

  35. IsmaelNiz's avatar IsmaelNiz says:

    Aw, this was a very good post. Taking a few minutes and actual effort to produce a good article… but what can I say… I put things off a lot and never seem to get nearly anything done.
    free spins no deposit

  36. What’s up, all is going sound here and ofcourse every one is sharing information, that’s really fine, keep up writing.

  37. Michaelkeymn's avatar Michaelkeymn says:

    vet pharmacy online vet pharmacy online pet rx

  38. IsmaelNiz's avatar IsmaelNiz says:

    Hello there! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really enjoy your content. Please let me know. Many thanks
    Download chicken road game 2 today.

  39. spinph's avatar spinph says:

    you’re truly a excellent webmaster. The website loading pace is amazing. It sort of feels that you’re doing any distinctive trick. Furthermore, The contents are masterpiece. you’ve done a magnificent activity on this topic!

  40. Williamclipt's avatar Williamclipt says:

    Mexican Pharm Mexican Pharm Mexican Pharm

  41. Williamclipt's avatar Williamclipt says:

    online pharmacies Mexican Pharm pharma mexicana

  42. JamesIdosy's avatar JamesIdosy says:

    order antibiotics from mexico: Mexican Pharm – Mexican Pharm

  43. Link exchange is nothing else but it is just placing the other person’s webpage link on your page at suitable place and other person will also do same for you.

  44. I’m amazed, I have to admit. Seldom do I encounter a blog that’s both educative and amusing, and without a doubt, you have hit the nail on the head. The issue is something which too few men and women are speaking intelligently about. I am very happy that I found this in my hunt for something regarding this.

  45. betmexico's avatar betmexico says:

    Thanks for sharing such a pleasant thinking, post is pleasant, thats why i have read it fully

  46. ZaimSelect's avatar ZaimSelect says:

    Здесь вы найдете мфо которые чаще одобряют займы сформирован как понятная подборка для быстрого старта для тех, кто хочет быстро понять, какие предложения по займам вообще доступны. Здесь можно выбрать подходящие направления, изучить микрозаймы на карту, микрокредиты от 18 лет, варианты для срочного оформления и отдельные подборки по условиям. Такой формат подходит не только тем, кто уже планирует взять займ, но и тем, кто сначала хочет сравнить разные направления без лишнего поиска по сайту.

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

    В этом разделе удобно искать не одну конкретную МФО, а сразу разные направления: займы с высоким шансом одобрения, микрозаймы на карту, займы с быстрым рассмотрением, условия для новых клиентов, предложения без большого пакета документов и МФО с быстрым переводом денег. Это помогает не тратить время на хаотичный поиск, сравнить предложения по смыслу и перейти к нужному типу займа без долгого просмотра разных материалов.

  47. I was recommended this web site by my cousin. I’m now not positive whether or not this publish is written through him as nobody else recognize such exact about my trouble. You’re amazing! Thanks!

  48. KreditNavi's avatar KreditNavi says:

    В этом разделе все варианты займов онлайн размещен как простая основа для выбора для тех, кто хочет сразу увидеть, какие предложения по займам вообще доступны. Здесь можно найти предложения микрофинансовых организаций, сравнить займы на карту, варианты для заемщиков от 18 лет, быстрые онлайн-займы и разные подборки по требованиям. Такой формат удобен не только тем, кто уже планирует взять займ, но и тем, кто сначала хочет выбрать подходящий тип займа без лишнего поиска по сайту.

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

    В этом разделе удобно искать не одну конкретную МФО, а сразу несколько типов предложений: предложения с мягкими требованиями, займы с переводом на карту, займы с быстрым рассмотрением, варианты для первого обращения, микрозаймы с минимальными документами и подборки компаний с быстрой выдачей. Это помогает сразу перейти к нужному направлению, не пропустить подходящие условия и перейти к нужному типу займа без долгого просмотра разных материалов.

Leave a Reply

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