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

    stromectol online canada stromectol Vip ivermectin where to buy for humans

  2. Right away I am ready to do my breakfast, after having my breakfast coming over again to read more news.

  3. Thankfulness to my father who shared with me on the topic of this web site, this webpage is genuinely amazing.

  4. LewisGor's avatar LewisGor says:

    Hello, this weekend is fastidious for me, since this occasion i am reading this fantastic informative article here at my home.
    在线购买无处方安定片 xxx Pornhub

  5. Howdy! Do you use Twitter? I’d like to follow you if that would be okay. I’m definitely enjoying your blog and look forward to new posts.

  6. EarnestCor's avatar EarnestCor says:

    Hi I am so delighted I found your blog page, I really found you by error, while I was looking on Aol for something else, Anyways I am here now and would just like to say thanks for a incredible 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 moment but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the great job.
    cialis pills sexual xxx porn pills

  7. GichardAmomi's avatar GichardAmomi says:

    What’s up Dear, are you really visiting this website on a regular basis, if so after that you will definitely obtain fastidious know-how.
    在线购买大麻用于XXX成人色情视频

  8. GichardAmomi's avatar GichardAmomi says:

    I think that what you published was very reasonable. However, consider this, what if you were to create a killer post title? I am not saying your content is not solid, but suppose you added a post title that grabbed a person’s attention? I mean %BLOG_TITLE% is kinda plain. You might peek at Yahoo’s front page and watch how they create post titles to get viewers to open the links. You might add a video or a pic or two to get readers excited about everything’ve got to say. In my opinion, it would make your posts a little bit more interesting.
    casino en ligne fiable

  9. Stanleyuteme's avatar Stanleyuteme says:

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

  10. RogerEmbow's avatar RogerEmbow says:

    Cheap Cialis cheapest cialis Cialis without a doctor prescription

  11. I could not refrain from commenting. Very well written!

  12. IsmaelNiz's avatar IsmaelNiz says:

    An outstanding share! I have just forwarded this onto a co-worker who has been doing a little research on this. And he actually ordered me dinner because I discovered it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for spending time to talk about this topic here on your web page.
    แทงหวย

  13. ChrisTok's avatar ChrisTok says:

    Viagra online price Buy generic 100mg Viagra online viagra canada

  14. ChrisTok's avatar ChrisTok says:

    viagra without prescription Viagra online price Cheap Sildenafil 100mg

  15. EliasZooni's avatar EliasZooni says:

    Формат помощи выбирают не по принципу «как удобнее», а по тому, насколько стабильно состояние и каков риск осложнений. Один и тот же диагноз «запой» может выглядеть по-разному: у кого-то ведущая проблема — давление и тахикардия, у другого — выраженная тревога и бессонница, у третьего — сильная тошнота и обезвоживание, у четвёртого — спутанность сознания или признаки психотических симптомов. Именно поэтому первое, что делает врач, — собирает информацию о длительности употребления, времени последнего приёма, сопутствующих заболеваниях, аллергиях и лекарствах, которые человек принимал самостоятельно. После этого проводится очная оценка: на дому или в клинике.
    Разобраться лучше – anonimnaya-narkologicheskaya-klinika

  16. Danielemulp's avatar Danielemulp says:

    В «Южном МедКонтроле» лечение зависимостей строится поэтапно, с постепенным восстановлением физиологических функций и эмоциональной устойчивости. Врачи используют современные методы детоксикации, фармакотерапию и психотерапию, которые действуют комплексно. Каждый этап направлен на достижение конкретного результата: очищение организма, снятие симптомов абстиненции, стабилизацию состояния и профилактику срывов.
    Подробнее тут – [url=https://narkologicheskaya-clinika-v-rostove19.ru/]платная наркологическая клиника ростов-на-дону[/url]

  17. It’s an remarkable article for all the web people; they will obtain advantage from it I am sure.

  18. phfun's avatar phfun says:

    Have you ever considered about including a little bit more than just your articles? I mean, what you say is important and everything. However think of if you added some great photos or video clips to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could certainly be one of the best in its niche. Excellent blog!

  19. Woah! I’m really loving the template/theme of this site. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between superb usability and visual appearance. I must say you’ve done a amazing job with this. Also, the blog loads super fast for me on Firefox. Exceptional Blog!

  20. horror game's avatar horror game says:

    I really like your wordpress web template, wherever did you down load it from?

  21. game horror's avatar game horror says:

    I was recommended this blog via my cousin. I am not sure whether or not this publish is written by way of him as nobody else know such specific about my difficulty. You’re incredible! Thank you!

  22. Исторические сведения о фамилиях представлены на https://poisk-familii.ru/

  23. 18bet's avatar 18bet says:

    I have read some good stuff here. Certainly worth bookmarking for revisiting. I wonder how so much attempt you put to make this type of excellent informative web site.

  24. What’s up colleagues, how is everything, and what you would like to say regarding this piece of writing, in my view its in fact amazing in favor of me.

  25. Craiggairm's avatar Craiggairm says:

    Premium THCA choicest isn’t lately organic and functional mushroom gummies around potency; it’s a sensory feast. Laughable in fragrant terpenes, these buds lay it on thick unlikely flavor profiles ranging from perfumed citrus to deep, piney diesel. When you ardour and inhale THCA blossom, these terpenes charge together with the activated cannabinoids to create a fuller, richer experience. It’s a actual celebration of the root’s imbecile complexity.

  26. Michaelpoick's avatar Michaelpoick says:

    The THCA flower stands out precise away with its still wet behind the ears fragrance, well turned out nature, and disinfected presentation. thc pain relief cream is a nearby recourse when something hurried and base is preferred. The THC cream also feels lightweight on the pellicle and has a pleasant finish. Entire lot looks carefully prepared, and the comprehensive supremacy feels dependable without being overcomplicated.

  27. JamesHot's avatar JamesHot says:

    Алкогольная зависимость часто держится не на «желании выпить», а на страхе отмены. Человек пьёт, чтобы не столкнуться с тремором, потливостью, тошнотой, скачками давления, паникой и бессонницей. Поэтому помощь начинается с медицинской оценки: насколько состояние безопасно для прекращения, какие есть сопутствующие болезни, что усиливает риски и какой формат лечения нужен именно сейчас.
    Получить дополнительную информацию – https://narkologicheskaya-klinika-orekhovo-zuevo2-12.ru/vrach-narkologicheskaya-klinika-v-orekhovo-zuevo

  28. Lamarhicle's avatar Lamarhicle says:

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

  29. KermitBaike's avatar KermitBaike says:

    https://freshpharm24.com/ safe online pharmacies

  30. This website was… how do I say it? Relevant!! Finally I’ve found something which helped me. Cheers!

  31. Jessiecus's avatar Jessiecus says:

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

  32. MichaelTob's avatar MichaelTob says:

    Реализация данных задач позволяет наркологу на дом в Ростове-на-Дону оказывать помощь в контролируемом и безопасном формате.
    Получить больше информации – врач нарколог на дом

  33. KermitBaike's avatar KermitBaike says:

    https://freshpharm24.com/ reputable overseas online pharmacies

  34. Thank you for sharing your info. I truly appreciate your efforts and I am waiting for your further write ups thank you once again.

  35. Kevinnonna's avatar Kevinnonna says:

    https://freshpharm24.com/ best mail order pharmacy

  36. Kevinnonna's avatar Kevinnonna says:

    https://freshpharm24.com/ online pharmacies

  37. codere's avatar codere says:

    Hey there! This post could not be written any better! Reading through this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Fairly certain he will have a good read. Thank you for sharing!

  38. xojili's avatar xojili says:

    Excellent items from you, man. I’ve be aware your stuff prior to and you’re simply too magnificent. I actually like what you’ve obtained here, really like what you are saying and the way by which you assert it. You make it entertaining and you continue to take care of to stay it wise. I cant wait to learn far more from you. This is really a wonderful site.

  39. sa影视's avatar sa影视 says:

    命运交错再度相遇,感人至深的爱情故事绽放,总会再相见

  40. ph888's avatar ph888 says:

    I do accept as true with all of the ideas you have offered on your post. They’re really convincing and will certainly work. Nonetheless, the posts are very short for newbies. May you please extend them a little from subsequent time? Thank you for the post.

  41. big win's avatar big win says:

    Pretty! This has been an incredibly wonderful article. Thanks for supplying these details.

  42. Martinloaby's avatar Martinloaby says:

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

Leave a Reply

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