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

    Tadalafil Tablet https://mensrxguide.org/# Generic Cialis price

  2. winland's avatar winland says:

    Keep on working, great job!

  3. betflik's avatar betflik says:

    hello there and thank you for your info –
    I’ve definitely picked up something new from right
    here. I did however expertise some technical
    points using this web site, since I experienced to reload the site a lot of times previous to I could get it to load correctly.

    I had been wondering if your web hosting is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and could damage your quality score if ads and marketing with Adwords.
    Well I am adding this RSS to my email and can look out for much more of your respective interesting content.
    Ensure that you update this again soon. betflik

  4. mr fortune's avatar mr fortune says:

    Howdy, I do think your blog could possibly be having browser compatibility issues. When I look at your site in Safari, it looks fine however when opening in Internet Explorer, it’s got some overlapping issues. I just wanted to provide you with a quick heads up! Besides that, excellent website!

  5. ClintSig's avatar ClintSig says:

    Viagra without a doctor prescription Canada Cheap generic Viagra – order viagra

  6. Georgeweisk's avatar Georgeweisk says:

    Нарколог на дом в Москве требуется в ситуации, когда человек после алкоголя не может самостоятельно восстановиться, находится в состоянии выраженной интоксикации, запоя, похмельного синдрома или абстиненции. В таком случае вызов врача на дом помогает быстро оценить состояние пациента, провести осмотр, подобрать препараты и начать лечение без лишней транспортировки. Дом становится местом первичной медицинской помощи, если врач видит, что процедуры можно провести безопасно в домашних условиях.
    Детальнее – https://narkolog-na-dom-moskva13.ru/vrach-narkolog-na-dom-moskva

  7. DichaelAlono's avatar DichaelAlono says:

    Excellent post. Keep writing such kind of info on your page. Im really impressed by your site.
    Hey there, You’ve performed an incredible job. I will definitely digg it and for my part recommend to my friends. I am sure they’ll be benefited from this web site.
    https://vedanta.dp.ua/test-na-adheziyu-yakyi-hermetyk-naikrashche.html

  8. IsmaelNiz's avatar IsmaelNiz says:

    Can I just say what a comfort to discover someone who actually understands what they are discussing on the net. You certainly know how to bring an issue to light and make it important. More and more people ought to check this out and understand this side of your story. I was surprised you are not more popular since you surely possess the gift.

    https://www.google.com.gt/maps/d/edit?mid=19AtLdzN4g2yRL8mjew8R2pIlZz5fp_0

  9. JasonsoynC's avatar JasonsoynC says:

    «Триумф» предоставляет широкий спектр наркологических услуг, покрывающий все этапы работы с зависимостью. Независимо от того, требуется ли экстренное выведение из запоя, плановое кодирование или длительная реабилитация, наши врачи подбирают эффективные и безопасные методы, соответствующие тяжести конкретного случая. Мы успешно лечим алкоголизм, наркоманию, игроманию, неврозы и другие расстройства. Подробнее ознакомиться с перечнем услуг можно на страницах сайта или по телефону. Наши специалисты — кандидаты наук, психиатры высшей категории, такие как Марина Олеговна, Александр Игоревич, Евгений Юрьевич и другие, — имеют огромный опыт борьбы с зависимостями. Чтобы записаться на приём или вызвать врача на дом, оставьте заявку онлайн на официальном сайте.
    Разобраться лучше – https://narkologicheskaya-klinika-moskva13.ru/chastnaya-narkologicheskaya-klinika-moskva

  10. LewisGor's avatar LewisGor says:

    Thank you for the auspicious writeup. It if truth be told was a leisure account it. Look complicated to more introduced agreeable from you! However, how could we keep in touch?
    meilleur casino en ligne sans wager

  11. Randallicema's avatar Randallicema says:

    https://urohealthdaily.shop/# Buy generic 100mg Viagra online

  12. AnthonyJoiff's avatar AnthonyJoiff says:

    Cheap generic Viagra Order Viagra 50 mg online – sildenafil over the counter

  13. AnthonyJoiff's avatar AnthonyJoiff says:

    Cheap generic Viagra online viagra without prescription – Viagra without a doctor prescription Canada

  14. AnthonyNup's avatar AnthonyNup says:

    Это основа детоксикации. Внутривенно вводятся солевые растворы, витаминные комплексы, гепатопротекторы и другие препараты, которые очищают кровь от токсинов, восстанавливают водно-электролитный баланс и поддерживают работу сердца и почек. Такая терапия эффективно снимает симптомы абстиненции, нормализует сон и общее самочувствие пациента. Врач контролирует дозировку и состав капельницы в зависимости от состояния больного и результатов анализов. Процедура чистка организма от токсинов позволяет не только вывести наркотики, но и восстановить работу печени и сердечно-сосудистой системы. Это базовый этап лечения зависимости, без которого невозможна полноценная реабилитация.
    Ознакомиться с деталями – http://detoksikaciya-narkomanov-moskva13.ru/

  15. JoshuaNet's avatar JoshuaNet says:

    pharmacy order online Victo Pharm п»їinternational drug mart

  16. LhanepiliA's avatar LhanepiliA says:

    What’s up to every single one, it’s in fact a good for me to pay a quick visit this web site, it contains helpful Information.
    paysafecard casino bonus

  17. Russellgulty's avatar Russellgulty says:

    weight loss semaglutide glp-1 drugs over the counter semaglutide cheap

  18. Donaldtix's avatar Donaldtix says:

    liraglutide online buy victoza liraglutide online

  19. DavidhaM's avatar DavidhaM says:

    Цена капельницы от запоя в Иркутске зависит от ряда факторов, таких как выбор метода лечения (на дому или в стационаре), продолжительность лечения и степень тяжести состояния пациента. Для уточнения стоимости и записи на консультацию вы можете обратиться к нашим менеджерам, которые подробно расскажут о стоимости услуг и ответят на все ваши вопросы.
    Выяснить больше – http://kapelnica-ot-zapoya-irkutsk3.ru/kapelnica-ot-zapoya-na-domu-v-irkutske/

  20. Stephenviaps's avatar Stephenviaps says:

    Pretty! This was a really wonderful article. Many thanks for providing these details.
    casino en ligne retrait instantane

  21. GeorgeGog's avatar GeorgeGog says:

    what are the most common side effects of rybelsus glp 1 pills semaglutide and diarrhea

  22. Jessegaf's avatar Jessegaf says:

    https://victopharm.shop/# worldwide pharmacy online

  23. Hello! I’ve been following your weblog for a long time now and finally got the bravery to go ahead and give you a shout out from Atascocita Tx! Just wanted to tell you keep up the good work!

  24. My wife and i got now cheerful when Ervin managed to finish up his preliminary research using the precious recommendations he had from your very own web page. It’s not at all simplistic to simply be giving out facts that some people may have been trying to sell. And we know we need the website owner to thank because of that. These illustrations you made, the simple web site menu, the friendships your site help to promote – it is mostly incredible, and it is aiding our son and the family do think this situation is enjoyable, and that’s seriously pressing. Thank you for all the pieces!

  25. onhour's avatar onhour says:

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

    onhour.ru: Ключевые направления работ
    Мелкий ремонт: Мастер на час оперативно устранит Мастер на час протечку крана, установит смеситель, соберет мебель или Муж на час в Москве починит дверную ручку.
    Электромонтажные услуги: Грамотный Муж на час безопасно заменит розетку, выключатель, Муж на час смонтирует светильник или подключит бытовую технику.
    Сантехнические работы: Вызов Муж на час в Москве — это замена шлангов, устранение засоров, Мастер на час монтаж полотенцесушителя или установка унитаза.
    Помощь с монтажом: Надежный Мастер на час Москва повесит тяжелые Мастер на час Москва зеркала, картины, карнизы, Мастер на час Москва соберет детский спортивный комплекс или установит технику.

    Мастер на час: Преимущества профессионального подхода
    Обращаясь к проверенному Муж на час, вы получаете не просто физическую помощь, а комплекс преимуществ:
    1. Экономия времени: Квалифицированный Мастер на час Москва выполнит задачу в разы быстрее.
    2. Качество и гарантия: Опытный Муж на час в Москве дает гарантию на свои работы.
    3. Решение «под ключ»: Хороший Муж на час в Москве приедет со своим инструментом и материалами.
    4. Безопасность: Профессиональный Мастер на час соблюдает технику безопасности.

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

  26. Robertwroft's avatar Robertwroft says:

    Вызвать нарколога на дом можно в любой район Москвы, врач приезжает в течение часа.
    Ознакомиться с деталями – https://narkolog-na-dom-moskva13-1.ru/vrach-narkolog-na-dom-moskva/

  27. togel4d's avatar togel4d says:

    It?s actually a cool and helpful piece of information. I?m glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  28. Jessiecus's avatar Jessiecus says:

    Нарколог устанавливает внутривенную капельницу, через которую вводятся растворы, обеспечивающие быстрое выведение токсинов, восстановление водно-электролитного баланса и стабилизацию состояния.
    Изучить вопрос глубже – вызов нарколога на дом воронеж.

  29. Orvalbop's avatar Orvalbop says:

    Алкогольная зависимость сопровождается не только физическими, но и глубокими психоэмоциональными проблемами. Психотерапевтическая помощь играет важную роль в лечении, помогая пациенту осознать причины зависимости и разработать стратегии для предотвращения рецидивов.
    Изучить вопрос глубже – https://narcolog-na-dom-ufa0.ru/

  30. GeorgeGog's avatar GeorgeGog says:

    us pharmacy no prescription legitimate online pharmacy buy online medicine

  31. Fobertnap's avatar Fobertnap says:

    Wow that was unusual. I just wrote an very long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say excellent blog!
    casino en ligne depot 10 euros

  32. RogerEmbow's avatar RogerEmbow says:

    ivermectin 4 tablets price stromectol Vip stromectol liquid

  33. mvp1688's avatar mvp1688 says:

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

  34. I?m impressed, I must say. Actually not often do I encounter a blog that?s each educative and entertaining, and let me inform you, you’ve hit the nail on the head. Your concept is outstanding; the difficulty is one thing that not enough people are speaking intelligently about. I am very blissful that I stumbled throughout this in my seek for something regarding this.

  35. EarnestCor's avatar EarnestCor says:

    Do you have a spam issue on this website; I also am a blogger, and I was wanting to know your situation; many of us have developed some nice methods and we are looking to trade methods with other folks, please shoot me an e-mail if interested.
    viagra pills sexual xxx porn pills

  36. O mod que fixou o tópico do stop-loss chamou o Dragon Hatch 2 de “o único honesto” — meio brincando, meio não.

  37. 888casino's avatar 888casino says:

    It’s wonderful that you are getting thoughts from this piece of writing as well as from our argument made here.

  38. Fobertnap's avatar Fobertnap says:

    Fantastic website you have here but I was curious if you knew of any message boards that cover the same topics talked about in this article? I’d really like to be a part of group where I can get responses from other experienced people that share the same interest. If you have any recommendations, please let me know. Appreciate it!
    casino en ligne depot 10 euros

  39. EarnestCor's avatar EarnestCor says:

    This is very interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your magnificent post. Also, I have shared your site in my social networks!
    在线购买他达拉非片用于肛交XXX色情

  40. Danielthymn's avatar Danielthymn says:

    Наши специалисты используют эффективные методы детоксикации, которые помогают быстро устранить физическую тягу к наркотикам и нормализовать работу внутренних органов. Индивидуальный подход к каждому больному, грамотный подбор лекарственных средств и многолетний опыт врачей-наркологов гарантируют высокие результаты лечения. Здесь вы найдете всю необходимую информацию о том, как проходит детоксикация от наркотиков в нашем центре, какие методики применяются и почему так важно не откладывать обращение за профессиональной помощью. Мы также даем подробные рекомендации родственникам наркозависимых, помогая им правильно вести себя в кризисной ситуации и преодолеть страх осуждения. Мотивация больного на прохождение полного курса лечения — ключевой фактор, и наши психологи уделяют этому особое внимание.
    Углубиться в тему – стоимость детоксикации от наркотиков в клинике

  41. Leonardroubs's avatar Leonardroubs says:

    Главная задача — сделать состояние управляемым: уменьшить тошноту, тремор, потливость, головную боль, «туман» в голове, снизить тревогу, выровнять показатели, помочь восстановить сон. При этом важно сохранять реалистичные ожидания: после длительного запоя организм истощён, поэтому слабость и эмоциональная нестабильность могут сохраняться некоторое время. Ключевой показатель качества помощи — не обещание «идеально за час», а безопасная динамика и понятные ориентиры на первые сутки.
    Подробнее тут – https://vyvod-iz-zapoya-klin12.ru

Leave a Reply

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