.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. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty is a Senior SW Engineer for CNH and he was 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 Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

1,427 Responses to .NET APIs Part 5 – All the CRUD APIs

  1. uspin88's avatar uspin88 says:

    229802 341319Thanks – Enjoyed this post, can you make it so I receive an e-mail when you make a fresh post? From Online Shopping Greek 985005

  2. uspin88's avatar uspin88 says:

    644233 152782Thank you for your very good info and feedback from you. car dealers san jose 404750

  3. serviceMuh's avatar serviceMuh says:

    Сломался и отключается без причины? Sony сервисный центр просто оставь заказ на обратный звонок, и всё уточнят

  4. OLanepiliA's avatar OLanepiliA says:

    you are really a excellent webmaster. The website loading velocity is incredible. It sort of feels that you are doing any unique trick. In addition, The contents are masterwork. you’ve done a excellent process on this topic!
    реристрация Dragon Money Casino

  5. IsmaelNiz's avatar IsmaelNiz says:

    This information is invaluable. How can I find out more?
    BanzaiBet

  6. serviceMuh's avatar serviceMuh says:

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

  7. MichaelTox's avatar MichaelTox says:

    В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
    А есть ли продолжение? – https://vi.apra.vn/binh-luan-cac-quy-dinh-phap-luat-ve-chu-the-nop-don-yeu-cau-thu-tuc-pha-san

  8. Larryloamn's avatar Larryloamn says:

    В данной статье вы найдете комплексный подход к изучению насущных тем. Мы комбинируем теоретические сведения с практическими советами, чтобы читатель мог не только понять проблему, но и найти пути её решения.
    Более того — здесь – https://ara-came.com/prospia-brank

  9. The One strain
    Very informative blog, highly recommended

  10. 749017 650718Hello, Neat post. Theres an issue together with your website in internet explorer, may check this? IE nonetheless will be the marketplace leader and a huge component to folks will omit your wonderful writing because of this issue. 331728

  11. It’s genuinely very difficult in this active life to listen news on TV,
    therefore I just use internet for that purpose, and take the hottest
    information.

  12. Matthewimpab's avatar Matthewimpab says:

    Дезинфекция в Питере! Комнаты, Особняки, Кабинеты. Квалифицированный сервис по приемлемым предложениям. Время для семьи и развлечений! Оформите заказ уборку прямо сейчас! Двигайтесь к https://uborka-top24.ru/

  13. Fobertnap's avatar Fobertnap says:

    Hi Dear, are you truly visiting this site daily, if so then you will absolutely get nice know-how.
    kra41 cc

  14. Planning's avatar Planning says:

    Cabinet IQ
    8305 State Hwy 71 #110, Austin,
    TX 78735, United Ⴝtates
    254-275-5536
    Planning

  15. serviceMuh's avatar serviceMuh says:

    Поломка уже серьезная, я бы ник кого не слушал и нес устройство в сервисный центр, возможно этот сервис поможет с вашей поломкой, оставь заказ на обратный звонок и тебе перезвонят через 5 минут, ну а дальше расскажут стоит ли вообще чинить твое устройство

  16. cheap vpns's avatar cheap vpns says:

    I was able to find good advice from your articles.

  17. 179908 331222Thank you for your data and respond to you. auto loans westvirginia 941068

  18. serviceMuh's avatar serviceMuh says:

    Поломка уже серьезная, я бы ник кого не слушал и нес устройство в сервисный центр, возможно этот сервисный центр поможет с вашей поломкой, оставь заказ на обратный звонок и тебе перезвонят через 5 минут, ну а дальше расскажут стоит ли вообще чинить твое устройство

  19. 412584 887903fantastic work Outstanding weblog here! Also your web site a whole lot up rapidly! What web host are you the usage of? Can I get your associate link on your host? I want my site loaded up as quick as yours lol 270652

  20. LewisGor's avatar LewisGor says:

    The other day, while I was at work, my sister stole my iPad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
    http://bagit.com.ua/yaki-shchipci-krasche-dlya-znjattja-sklua-ta-korpusu-fary

  21. Timsothybioli's avatar Timsothybioli says:

    Hi there friends, its fantastic piece of writing concerning teachingand entirely explained, keep it up all the time.
    официальный сайт Banda Casino

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

  23. LhanepiliA's avatar LhanepiliA says:

    What a stuff of un-ambiguity and preserveness of valuable knowledge about unpredicted emotions.
    регистрация казино либет

  24. LewisGor's avatar LewisGor says:

    Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a bit, but instead of that, this is fantastic blog. A great read. I’ll certainly be back.
    leebet

  25. Timsothybioli's avatar Timsothybioli says:

    Awesome! Its actually remarkable post, I have got much clear idea on the topic of from this article.
    http://bagit.com.ua/yak-steklo-fary-mozhe-znyzyty-ryzyk-polomok-avtomo.html

  26. 94798 582103Some actually great info , Gladiola I located this. 499030

  27. cams sex's avatar cams sex says:

    Since the admin of this site is working, no question very soon it
    will be famous, due to its quality contents.

  28. vg98's avatar vg98 says:

    82882 662095Chaga mushroom tea leaf is thought-about any adverse health elixir at Spain, Siberia and a lot of n . Countries in europe sadly contains before you go ahead significantly avoidable the main limelight under western culture. Mushroom 767532

  29. Stephenviaps's avatar Stephenviaps says:

    Good post. I learn something new and challenging on websites I stumbleupon every day. It’s always exciting to read through content from other authors and use a little something from other sites.
    zumospin iDEAL

  30. Cabinet IQ
    15030 N Tatum Blvd #150, Phoenix,
    AZ 85032, United Stɑtes
    (480) 424-4866
    Innovationkitchen

  31. 603476 137506I always pay a visit to your weblog and retrieve everything you post here but I never commented but today when I saw this post, I couldnt stop myself from commenting here. Wonderful post mate! 183520

  32. LhanepiliA's avatar LhanepiliA says:

    I think that everything said made a lot of sense. However, what about this? what if you were to create a awesome title? I am not saying your content is not good., but what if you added something to possibly get people’s attention? I mean %BLOG_TITLE% is kinda plain. You might look at Yahoo’s front page and note how they create article titles to get viewers to click. You might add a related video or a picture or two to get people excited about everything’ve got to say. In my opinion, it would bring your posts a little livelier.
    http://blooms.com.ua/yak-pravylno-vybyraty-steklo-fara-dlya-retro-avtom.html

  33. IsmaelNiz's avatar IsmaelNiz says:

    What’s up, I want to subscribe for this website to get latest updates, so where can i do it please help.
    https://100zakazov.ru/

  34. Liptkal's avatar Liptkal says:

    At this moment I am going away to do my breakfast, later than having my breakfast
    coming yet again to read additional news.

  35. 289474 484418Very properly written story. It is going to be valuable to everybody who utilizes it, as nicely as myself. Maintain up the good function – i will certainly read much more posts. 512246

  36. Refresh Renovation Southwest Charlotte
    1251 Arrow Pine Ɗr с121,
    Charlotte, NC 28273, Unied Ѕtates
    +19803517882
    And case renovation ideas studies

  37. LewisGor's avatar LewisGor says:

    Trade, earn points, and explore Web3 projects on Asterdex
    — your gateway to decentralized markets.
    I’ve been using Asterdex
    lately — cool platform where you can trade, collect points, and track crypto trends in one place.
    With Asterdex
    , users can trade assets, earn rewards, and explore data from multiple blockchains in real time.
    Check out Asterdex
    — you can trade, earn points, and discover trending tokens fast. ??
    официальный сайт кэт казино

  38. LewisGor's avatar LewisGor says:

    Trade, earn points, and explore Web3 projects on Asterdex
    — your gateway to decentralized markets.
    I’ve been using Asterdex
    lately — cool platform where you can trade, collect points, and track crypto trends in one place.
    With Asterdex
    , users can trade assets, earn rewards, and explore data from multiple blockchains in real time.
    Check out Asterdex
    — you can trade, earn points, and discover trending tokens fast. ??
    astrr dex

  39. EarnestCor's avatar EarnestCor says:

    It’s amazing in favor of me to have a web site, which is helpful in support of my know-how. thanks admin
    официальный сайт lee bet

  40. LhanepiliA's avatar LhanepiliA says:

    Hmm is anyone else experiencing problems with the images on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.
    https://abank.com.ua/ekstruder-dlia-hermetyka-shcho-potribno-znaty.html

  41. Grape Runtz strain
    Thanks for sharing this valuable information.

  42. Bennie's avatar Bennie says:

    Migvhty Dog Roofing
    Reimer Drive North 13768
    Maple Grove, MN 55311 United Ꮪtates
    (763) 280-5115
    Bookmarks (Bennie)

  43. IsmaelNiz's avatar IsmaelNiz says:

    Greetings I am so thrilled I found your website, I really found you by accident, while I was searching on Bing for something else, Nonetheless I am here now and would just like to say kudos for a tremendous post and a all round thrilling blog (I also love the theme/design), I don’t have time to read it all at the minute but I have saved 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 great job.
    keepstyle

  44. OLanepiliA's avatar OLanepiliA says:

    Why visitors still make use of to read news papers when in this technological world the whole thing is existing on web?
    keepstyle

  45. Stephenviaps's avatar Stephenviaps says:

    What’s up, its pleasant paragraph regarding media print, we all be aware of media is a great source of information.
    keepstyle

  46. Stephenviaps's avatar Stephenviaps says:

    Do you have a spam problem on this site; I also am a blogger, and I was curious about your situation; we have created some nice methods and we are looking to swap strategies with other folks, be sure to shoot me an email if interested.
    keepstyle

  47. 26611 28479Its superb as your other posts : D, regards for posting . 999304

  48. 532358 364986Thank you, Ive lately been looking for info about this topic for ages and yours will be the greatest Ive located out so far. But, what in regards to the bottom line? Are you sure concerning the supply? 201980

Leave a Reply

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