.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. 178380 8416Wow, amazing weblog layout! How long have you been blogging for? you make blogging look easy. The overall appear of your web website is fantastic, let alone the content material! 323366

  2. Stephenviaps's avatar Stephenviaps says:

    Greate pieces. Keep posting such kind of information on your blog. Im really impressed by it.
    Hi there, You have performed a great job. I’ll certainly digg it and individually recommend to my friends. I’m confident they’ll be benefited from this site.
    вход zooma casino

  3. OLanepiliA's avatar OLanepiliA says:

    The other day, while I was at work, my sister stole my iPad and tested to see if it can survive a thirty foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!
    официальный сайт lee bet casino

  4. IsmaelNiz's avatar IsmaelNiz says:

    Excellent post. Keep writing such kind of info on your site. Im really impressed by your blog.
    Hello there, You’ve done a great job. I’ll definitely digg it and for my part suggest to my friends. I’m confident they’ll be benefited from this website.
    официальный сайт lee bet

  5. LhanepiliA's avatar LhanepiliA says:

    This is really interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your great post. Also, I have shared your website in my social networks!
    регистрация RioBet

  6. 799900 492411I want reading by way of and I conceive this website got some really utilitarian stuff on it! . 32927

  7. LewisGor's avatar LewisGor says:

    Thanks for another informative site. Where else could I am getting that kind of information written in such a perfect way? I have a challenge that I’m just now running on, and I’ve been on the glance out for such information.
    https://eximp.com.ua/kachestvennye-stekla-i-korpusa-dlya-far-sovety-po-vyboru-komponentov

  8. 752086 263329I truly prize your piece of work, Excellent post. 372954

  9. 238456 263998I surely did not understand that. Learnt a thing new nowadays! Thanks for that. 442978

  10. Stephenviaps's avatar Stephenviaps says:

    It’s amazing to pay a quick visit this website and reading the views of all friends regarding this post, while I am also keen of getting know-how.
    кракен зеркало

  11. I was recommended this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my
    problem. You’re wonderful! Thanks!

    My web page … pink salt trick recipe

  12. ShanepiliA's avatar ShanepiliA says:

    Thanks for sharing your info. I really appreciate your efforts and I am waiting for your further post thanks once again.
    elonbet fishing

  13. LhanepiliA's avatar LhanepiliA says:

    Helpful info. Lucky me I found your website by chance, and I am stunned why this coincidence did not came about earlier! I bookmarked it.
    elonbet egypt melbet

  14. GichardAmomi's avatar GichardAmomi says:

    I appreciate, lead to I found exactly what I used to be having a look for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day. Bye
    sex children elon casino

  15. LewisGor's avatar LewisGor says:

    Heya this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get advice from someone with experience. Any help would be greatly appreciated!
    https://kra39at.org/

  16. Fobertnap's avatar Fobertnap says:

    Hey I am so thrilled I found your website, I really found you by accident, while I was browsing on Digg for something else, Anyhow I am here now and would just like to say thank you for a marvelous post and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the awesome job.
    kra39 at

  17. The things i have observed in terms of computer memory is that often there are specs such as SDRAM, DDR and the like, that must fit in with the specific features of the mother board. If the pc’s motherboard is fairly current while there are no operating system issues, modernizing the storage space literally normally requires under an hour or so. It’s among the easiest computer upgrade procedures one can imagine. Thanks for giving your ideas.

  18. OLanepiliA's avatar OLanepiliA says:

    Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is magnificent, as well as the content!
    kra39 cc

  19. 662339 863839I discovered your blog site internet web site on the internet and appearance some of your early posts. Continue to keep inside the wonderful operate. I just now additional increase your Rss to my MSN News Reader. Seeking toward reading far much more from you locating out at a later date! 724371

  20. DichaelAlono's avatar DichaelAlono says:

    I delight in, lead to I discovered exactly what I was having a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye
    интерент магазин посуды

  21. Ntctenuth's avatar Ntctenuth says:

    the best ways for men to lead rewarding sex lives in bed.End mirtazapine onset of action since it’s a successful treatment mirtazapine cost

  22. Betify fr's avatar Betify fr says:

    955388 208648Attractive section of content. I just stumbled upon your blog and in accession capital to assert that I acquire actually enjoyed account your blog posts. Anyway I will be subscribing to your augment and even I achievement you access consistently speedily. 227114

  23. Wow! Thank you! I constantly wanted to write on my website something like that. Can I implement a fragment of your post to my blog?

  24. Buy Best SEO's avatar Buy Best SEO says:

    Excellent items from you, man. I’ve consider your stuff previous to and you are simply extremely magnificent. I actually like what you’ve obtained right here, certainly like what you’re stating and the best way wherein you assert it. You make it enjoyable and you continue to take care of to stay it wise. I can’t wait to learn far more from you. That is really a tremendous site.

  25. Timsothybioli's avatar Timsothybioli says:

    Welcome to Bluevine login, your ultimate financial partner for small businesses. Our company provides advanced financial tools designed to simplify your financial operations and support your business expansion. Whether you need a line of credit or invoice factoring, Bluevine has you covered. To manage your account, simply use the secure Bluevine login portal, which allows you to control your finances with ease and confidence. Join thousands of satisfied entrepreneurs who trust Bluevine to advance their business.

  26. 565608 411271Thanks for the auspicious writeup. It truly used to be a leisure account it. Glance complicated to much more delivered agreeable from you! However, how can we be in contact? 629426

  27. checkslip's avatar checkslip says:

    919748 371124They call it the self-censor, merely because youre too self-conscious of your writing, too judgmental. 129278

  28. 852142 943916Cool post thanks! We think your articles are wonderful and hope far more soon. We really like anything to do with word games/word play. 809563

  29. 689560 234204I observe there is a lot of spam on this weblog. Do you require assist cleaning them up? I might support among classes! 545995

  30. 224506 941670Beging with the entire wales nicely before just about any planking. Our own wales can easily compilation of calculated forums those thickness analysts could be the similar to some of the shell planking along with far more significant damage so that they project right after dark planking. planking 557271

  31. IsmaelNiz's avatar IsmaelNiz says:

    What’s up it’s me, I am also visiting this site daily, this site is truly pleasant and the viewers are truly sharing nice thoughts.
    gemini

  32. Ernestcal's avatar Ernestcal says:

    бот для накрутки поведенческих факторов Поисковые системы, в частности Яндекс, используют поведенческие факторы для оценки качества и релевантности сайта. Ключевыми ПФ являются: время, проведенное пользователем на сайте, глубина просмотра (количество просмотренных страниц) и показатель отказов (процент пользователей, покинувших сайт сразу после перехода). Технологии накрутки ПФ: Monstro, Bydlocoder и другие игроки рынка

  33. Buy Best SEO's avatar Buy Best SEO says:

    I conceive this site has very great pent content material articles.

  34. kashpo napolnoe _baPr's avatar kashpo napolnoe _baPr says:

    напольный горшок для цветов купить напольный горшок для цветов купить .

  35. remontMuh's avatar remontMuh says:

    Данный сервисный центр поможет починить ваше устройство, держите информацию об этом сервисном центре

  36. Robert Wilson's avatar Robert Wilson says:

    Great explanation of CRUD APIs and how they apply in real projects. The clarity here helps developers avoid common mistakes. For a different perspective, exploring สาวไซด์ไลน์-fiwfan shows how structured connections matter in unexpected contexts.

  37. 123bet login's avatar 123bet login says:

    20756 729307Just wanna input on few common things, The web site style is perfect, the articles is extremely excellent : D. 302447

  38. new88's avatar new88 says:

    634630 633956conclusion that you are totally proper but a few need to be 885593

  39. 989814 676378Beging with the entire wales well before just about any planking. Our own wales can easily compilation of calculated forums those thickness analysts could be the related to some of the shell planking along with much more significant damage so that they project after dark planking. planking 243455

  40. 18915 733084Thank you for your quite very good data and respond to you. I want to verify with you here. Which isnt one thing I often do! I get pleasure from reading a publish that can make people think. Additionally, thanks for permitting me to remark! 919210

  41. 675122 371252Its difficult to get knowledgeable folks on this topic, but the truth is be understood as what happens youre preaching about! Thanks 953105

  42. 950095 732146You created some decent factors there. I looked on the internet for the problem and located most individuals will go along with with your internet site. 121792

  43. 50022 975059Thank you for this wonderful post! It has long been really helpful. I wish that you will carry on posting your knowledge with us. 828810

  44. vavada's avatar vavada says:

    Aby zalogować się do Vavada, będziesz potrzebować: Login – numer telefonu lub e-mail użyty podczas rejestracji Hasło – ustawione samodzielnie lub wygenerowane przez przeglądarkę Opcja „Zapamiętaj” pozwala przyspieszyć kolejne logowania. Jeśli gracz zapomni hasła, może skorzystać z przypomnienia lub skontaktować się z obsługą klienta.

  45. vavada's avatar vavada says:

    Proces tworzenia konta w Vavada jest bardzo prosty. Przycisk rejestracji znajduje się w prawym górnym rogu, obok przycisku logowania i czatu wsparcia. Każdy gracz może mieć tylko jedno konto.

Leave a Reply

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