.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,553 Responses to .NET APIs Part 5 – All the CRUD APIs

  1. 220924 555773Aw, this was a actually nice post. In thought I would like to location in writing in this way moreover – taking time and actual effort to create a very good article but what / points I say I procrastinate alot and also no indicates apparently get something done. 176473

  2. Fobertnap's avatar Fobertnap says:

    https://yandex.ru/profile/147633783627?lang=ru
    ООО “Мир ремней” – Производство приводных ремней, тефлоновых сеток и лент.
    Телефон +7 (936) 333-93-03

  3. OLanepiliA's avatar OLanepiliA says:

    This is my first time go to see at here and i am in fact impressed to read all at single place.
    bitcoin betting

  4. gorshok s avtopolivom_lvel's avatar gorshok s avtopolivom_lvel says:

    напольный горшок с автополивом http://kashpo-s-avtopolivom-kazan.ru/ .

  5. EarnestCor's avatar EarnestCor says:

    Admiring the dedication you put into your blog and detailed information you present. It’s good to come across a blog every once in a while that isn’t the same out of date rehashed material. Excellent read! I’ve saved your site and I’m adding your RSS feeds to my Google account.
    https://бц-кубик.рф

  6. Fobertnap's avatar Fobertnap says:

    Hey there! Would you mind if I share your blog with my twitter group? There’s a lot of people that I think would really enjoy your content. Please let me know. Many thanks
    банда казино

  7. testosterone bodybuilding forum

    References:

    Winni V Steroid; Forum.Issabel.Org,

  8. OLanepiliA's avatar OLanepiliA says:

    Right here is the right site for anyone who would like to understand this topic. You know a whole lot its almost hard to argue with you (not that I really will need to…HaHa). You certainly put a fresh spin on a topic that’s been discussed for years. Wonderful stuff, just excellent!
    https://www.australiansurffestival.com/led-ta-bi-led-linzi-riznytsya-perevagy-ta-vybir-dlya-avto

  9. DichaelAlono's avatar DichaelAlono says:

    Whats up are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding expertise to make your own blog? Any help would be greatly appreciated!
    https://e-comex.com.ua/linzi-u-fari-dovgovichnist-yakist-i-ekonomiya-palnogo

  10. ShanepiliA's avatar ShanepiliA says:

    Hi there, after reading this awesome paragraph i am as well delighted to share my familiarity here with friends.
    https://rent-in-odessa.com/avtosvitlo-2025-golovni-tekhnologii-ta-innovatsii-iaki-varto-znati.html

  11. dizainerskie kashpo_xySl's avatar dizainerskie kashpo_xySl says:

    оригинальные кашпо горшки для цветов http://www.dizaynerskie-kashpo-rnd.ru/ .

  12. ShanepiliA's avatar ShanepiliA says:

    Digital life demands accuracy. Engineers, researchers, students, and professionals rely on precise numbers and flawless documents. Yet the tools they need are often scattered across multiple apps, hidden behind subscriptions, or limited in scope. OneConverter addresses this challenge by consolidating advanced unit conversion calculators and PDF document utilities into a single, accessible platform.

    Comprehensive Unit Conversions
    The strength of OneConverter lies in its range. With more than 50,000 unit converters, it covers virtually every field of science, technology, and daily life.
    Core Measurements: conversions for length, weight, speed, temperature, area, volume, time, and energy. These fundamental tools support everyday requirements such as travel, shopping, and cooking.
    Engineering & Physics: advanced calculators for torque, density, angular velocity, acceleration, and moment of inertia, enabling precision in both academic study and professional design.
    Heat & Thermodynamics: tools for thermal conductivity, resistance, entropy, and enthalpy, providing clarity for scientific research and industrial applications.
    Radiology: units such as absorbed dose, equivalent dose, and radiation exposure, essential for healthcare professionals and medical physicists.
    Fluid Mechanics: viscosity, pressure, flow rate, and surface tension, all indispensable in laboratory and engineering environments.
    Electricity & Magnetism: extensive coverage including voltage, current, resistance, inductance, capacitance, flux, and charge density, supporting fields from electronics to energy.
    Chemistry: molarity, concentration, and molecular weight calculators, saving valuable time in laboratories and classrooms.
    Astronomy: astronomical units, parsecs, and light years, serving both researchers and students exploring the cosmos.
    Practical Applications: everyday conversions for recipes, fuel efficiency, and international clothing sizes.
    By combining breadth and accuracy, OneConverter ensures that calculations are reliable, consistent, and instantly available.
    oneconverter.com

  13. Если хотите испытать азарт и яркие эмоции, начните с самого первого шага — регистрация в Win.Casino. После этого вас ждёт огромный выбор слотов и возможность выиграть.

  14. IsmaelNiz's avatar IsmaelNiz says:

    Picture this: you’re cooking dinner and the recipe calls for grams, but your scale only shows ounces. Later, you’re helping your child with homework and suddenly need to convert meters per second into kilometers per hour. The next morning, you’re preparing a presentation and realize the client wants it in PDF format. Three different situations, three different problems – and usually, three different apps.
    That’s the hassle OneConverter eliminates. It’s an all-in-one online tool designed for people who want life to be simpler, faster, and smarter. No downloads, no subscriptions, no headaches – just answers, right when you need them.

    Unit Conversions Made Effortless
    Most conversion tools handle only the basics. OneConverter goes further – much further. With more than 50,000 unit converters, it can handle everyday situations, advanced academic work, and professional challenges without breaking a sweat.
    Everyday Basics: length, weight, speed, temperature, time, area, volume, energy.
    Engineering & Physics: torque, angular velocity, density, acceleration, moment of inertia.
    Heat & Thermodynamics: thermal conductivity, thermal resistance, entropy, enthalpy.
    Radiology: absorbed dose, equivalent dose, radiation exposure.
    Fluids: viscosity, flow rate, pressure, surface tension.
    Electricity & Magnetism: voltage, current, resistance, capacitance, inductance, flux.
    Chemistry: molarity, concentration, molecular weight.
    Astronomy: light years, parsecs, astronomical units.
    Everyday Extras: cooking measures, shoe and clothing sizes, fuel efficiency.

    From the classroom to the lab, from the office to your kitchen – OneConverter has a solution ready.
    OneConverter

  15. LhanepiliA's avatar LhanepiliA says:

    Students, professionals, and hobbyists alike rely on OneConverter.com as a trusted resource. High school students use it to complete homework questions, ensuring they understand how to convert between units of volume or temperature. College researchers appreciate its scientific precision when dealing with complex conversions in physics or engineering. Business professionals often need quick currency or time zone calculations to plan international meetings; this site delivers those results instantly. DIY enthusiasts measure materials for home improvement projects by converting square feet to square meters or gallons to liters. Photographers evaluate storage needs by converting between megabytes and gigabytes. Fitness trainers track distances and energy expenditure by switching between miles and kilometers or calories and kilojoules. With OneConverter, there’s no need to memorize dozens of conversion factors — just input your number, choose your units, and the answer appears. The clear layout and straightforward instructions help users learn as they go, making the site both a tool and a teaching aid. Regardless of your field or expertise level, OneConverter.com provides the conversions you need, right when you need them.
    OneConverter

  16. EarnestCor's avatar EarnestCor says:

    At WebPtoPNGHero.com, converting WebP images into PNG format couldn’t be simpler. The interface features a drag-and-drop area where images load instantly, and conversion begins on secure cloud servers. A progress meter keeps you informed, and once each file finishes, PNG versions appear as clickable download links. If you have many images to process, batch mode handles multiple files at the same time, saving precious minutes. The tool runs entirely in your web browser, making it compatible with Windows, macOS, Linux, Android, and iOS alike. No need to install any applications or plugins—just open the site and start converting. All uploads vanish shortly after processing, ensuring privacy and security. Whether you’re optimizing visuals for an e-commerce store, preparing photos for email attachments, or simply sharing snapshots online, WebPtoPNGHero.com delivers reliable, high-fidelity results. The service remains free and ad-free, with no registration required. Convert your WebP images to universally supported PNG files quickly and without hassle.
    WebPtoPNGHero

  17. 949399 363220I enjoy meeting utile info, this post has got me even more information! . 549673

  18. 489519 229028Extremely good style and style and wonderful topic matter, quite small else we want : D. 689408

  19. 784260 246308This douche bag loves his illegal bretheren because hes a itiaen of the world and we should be ashamed of ourselves I got news for you Asswipe get your asswiping ass back towards the craphole exactly where you came from with all of your illegal beaners 91733

  20. DichaelAlono's avatar DichaelAlono says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.
    casino sites

  21. 859243 544519Great V I should definitely pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. 962429

  22. Grapes and Cream strain
    Thanks for sharing this valuable information.

  23. GichardAmomi's avatar GichardAmomi says:

    Great site you have here but I was wondering if you knew of any community forums that cover the same topics discussed here? I’d really love to be a part of community where I can get responses from other knowledgeable individuals that share the same interest. If you have any suggestions, please let me know. Kudos!

    https://tutbonus.com/dota2/epicloot/

  24. OLanepiliA's avatar OLanepiliA says:

    Just desire to say your article is as astounding. The clarity to your submit is simply cool and i can think you’re knowledgeable on this subject. Fine together with your permission allow me to clutch your feed to stay updated with forthcoming post. Thanks one million and please keep up the rewarding work.
    https://ejameswest.com/

  25. 817304 303095I feel other site proprietors ought to take this web site as an model, really clean and superb user genial style . 650821

  26. 207556 230459A really fascinating read, I may properly not agree completely, but you do make some quite legitimate factors. 673849

  27. 717341 357349I real glad to locate this internet website on bing, just what I was searching for : D likewise saved to bookmarks . 306192

  28. 535954 786616This Los angeles Weight Loss diet happens to be an low and flexible going on a diet application meant for generally trying to drop the weight as nicely within the have a considerably healthier lifetime. lose weight 897261

  29. IsmaelNiz's avatar IsmaelNiz says:

    Wow, incredible blog structure! How long have you been running a blog for? you made blogging look easy. The full look of your site is excellent, let alone the content material!
    https://lkra39.at/

  30. ShanepiliA's avatar ShanepiliA says:

    you are really a excellent webmaster. The website loading velocity is incredible. It seems that you’re doing any unique trick. Moreover, The contents are masterpiece. you’ve performed a great activity in this matter!
    https://lkra39.at/

  31. LewisGor's avatar LewisGor says:

    I got this web site from my friend who told me on the topic of this web page and at the moment this time I am browsing this web page and reading very informative content at this place.
    кракен зеркало

  32. IsmaelNiz's avatar IsmaelNiz says:

    I’m gone to inform my little brother, that he should also visit this weblog on regular basis to get updated from latest news update.
    https://rainbetaustralia.com/

  33. ShanepiliA's avatar ShanepiliA says:

    That is really fascinating, You are a very professional blogger. I’ve joined your feed and look forward to seeking extra of your excellent post. Additionally, I’ve shared your site in my social networks
    Rain bet

  34. IsmaelNiz's avatar IsmaelNiz says:

    Howdy 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 knowledge so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!
    Cleobetra Casino Online

  35. ShanepiliA's avatar ShanepiliA says:

    What’s up mates, its wonderful post about cultureand fully explained, keep it up all the time.
    Cleobetra Casino Online

  36. Stephenviaps's avatar Stephenviaps says:

    Pretty! This was an extremely wonderful post. Thank you for providing this info.
    Cleobetra

  37. LewisGor's avatar LewisGor says:

    Thank you for every other informative site. The place else may just I get that type of info written in such a perfect means? I’ve a venture that I’m simply now operating on, and I’ve been at the look out for such info.
    Cleobetra Casino

  38. Timsothybioli's avatar Timsothybioli says:

    Hello! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?
    Cleobetra Casino Online

  39. Stephenviaps's avatar Stephenviaps says:

    Howdy! This post couldn’t be written any better! Reading through this post reminds me of my old room mate! He always kept chatting about this. I will forward this post to him. Fairly certain he will have a good read. Many thanks for sharing!
    Cleobetra

  40. MichaelLig's avatar MichaelLig says:

    Онлайн-казино Jozz популярно среди игроков.
    Акции и специальные предложения дают возможность играть без вложений.
    Турниры и соревнования делают процесс динамичным.
    Ассортимент игр включает топовых провайдеров.
    Вход доступен быстро, и сразу начать играть.
    Узнай больше здесь: https://zcarclubnova.org

  41. 840236 152675I observe there is a lot of spam on this blog. Do you want support cleaning them up? I may well assist in between courses! 564606

  42. GichardAmomi's avatar GichardAmomi says:

    Hello I am so glad I found your website, I really found you by error, while I was browsing on Askjeeve for something else, Regardless I am here now and would just like to say thanks a lot for a incredible post and a all round entertaining blog (I also love the theme/design), I don’t have time to read through 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 much more, Please do keep up the excellent work.
    официальный сайт leebet

Leave a Reply

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