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

    If you are going for most excellent contents like myself, simply pay a quick visit this website daily since it presents quality contents, thanks

  2. JamesIdosy's avatar JamesIdosy says:

    Canadian Tabs: canadian pharmacy victoza – Canadian Tabs

  3. Please let me know if you’re looking for a article author for your blog. You have some really great articles and I feel I would be a good asset. If you ever want to take some of the load off, I’d really like to write some content for your blog in exchange for a link back to mine. Please blast me an email if interested. Regards!

  4. Davidten's avatar Davidten says:

    januvia and rybelsus semaglutide life rybelsus,

  5. mexplay's avatar mexplay says:

    It is truly a great and helpful piece of info. I’m glad that you just shared this useful information with us. Please stay us informed like this. Thank you for sharing.

  6. melbet's avatar melbet says:

    Currently it appears like BlogEngine is the top blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?

  7. Excellent article. Keep posting such kind of information on your blog. Im really impressed by it

  8. What’s up mates, fastidious piece of writing and fastidious urging commented here, I am in fact enjoying by these.

  9. EliasLew's avatar EliasLew says:

    ivermectin cream cost: ivermectin 1 cream generic – ivermectin ebay

  10. Danielgek's avatar Danielgek says:

    https://antibiotics.cheap/# over the counter antibiotics

  11. Hello my friend! I wish to say that this article is awesome, nice written and include almost all vital infos. I would like to see more posts like this .

  12. Edgarpaype's avatar Edgarpaype says:

    rybelsus review: semaglutide 2.5 mg – medicine online

  13. ta777's avatar ta777 says:

    Hi, i think that i saw you visited my web site thus i came to “return the favor”.I am trying to find things to improve my web site!I suppose its ok to use a few of your ideas!!

  14. Davidten's avatar Davidten says:

    antibiotic without presription get antibiotics quickly over the counter antibiotics

  15. netbet's avatar netbet says:

    Hello this is kind of 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 experience so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

  16. Edgarpaype's avatar Edgarpaype says:

    stromectol drug: stromectol reviews – stromectol reviews

  17. EliasLew's avatar EliasLew says:

    stromectol reviews: stromectol reviews – buy stromectol online uk

  18. spb-inst's avatar spb-inst says:

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

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

  19. winland's avatar winland says:

    Hello colleagues, its great post regarding tutoringand fully defined, keep it up all the time.

  20. bodog's avatar bodog says:

    Nice replies in return of this difficulty with real arguments and telling all concerning that.

  21. spb-inst.ru's avatar spb-inst.ru says:

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

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

  22. EliasLew's avatar EliasLew says:

    buy stromectol canada: ivermectin for humans – ivermectin for humans

  23. Edgarpaype's avatar Edgarpaype says:

    antibiotics cheap: get antibiotics quickly – uti antibiotics online

  24. EliasLew's avatar EliasLew says:

    ivermectin pills canada: stromectol reviews – oral ivermectin cost

  25. Edgarpaype's avatar Edgarpaype says:

    stromectol reviews: ivermectin 6mg dosage – buy stromectol online

  26. pokerstars's avatar pokerstars says:

    Good response in return of this query with genuine arguments and describing everything concerning that.

  27. Hello There. I found your blog using msn. This is a very well written article. I’ll make sure to bookmark it and return to learn more of your helpful information. Thank you for the post. I will definitely return.

  28. Excellent website. Lots of helpful info here. I am sending it to a few pals ans also sharing in delicious. And naturally, thank you on your sweat!

  29. Edgarpaype's avatar Edgarpaype says:

    stromectol reviews: stromectol reviews – stromectol reviews

  30. Pedroatoky's avatar Pedroatoky says:

    https://semaglutide.life/# semaglutide cancer

  31. Jasonutery's avatar Jasonutery says:

    Pharm Rate: us pharmacy no prescription – Pharm Rate

  32. tayabet's avatar tayabet says:

    Wonderful, what a webpage it is! This website provides valuable facts to us, keep it up.

  33. sportium's avatar sportium says:

    It’s an awesome post for all the internet users; they will obtain advantage from it I am sure.

  34. CharlesFem's avatar CharlesFem says:

    online pharmacy discount code Pharm Rate Pharm Rate

  35. jojobet's avatar jojobet says:

    Do you have a spam problem on this site; I also am a blogger, and I was wondering your situation; many of us have created some nice methods and we are looking to swap methods with others, why not shoot me an e-mail if interested.

  36. manage.top's avatar manage.top says:

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

  37. Pedrohok's avatar Pedrohok says:

    cheap ed meds online: Ed Meds Coupon – online pharmacies

  38. PatrickZes's avatar PatrickZes says:

    https://edmedscoupon.com/# online ed treatments

  39. wjevo's avatar wjevo says:

    Hello there, I found your site by the use of Google while looking for a similar subject, your website got here up, it appears great. I’ve bookmarked it in my google bookmarks

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

    深宫秘史,后宫嫔妃之间的权谋与生死博弈。我的朋友安德烈高清免费看

  41. Kasmenadag's avatar Kasmenadag says:

    Для бизнеса сегодня вашему бизнесу manage top программа позволяет создать удобную систему работы без хаоса и бесконечных таблиц. В одном удобном окне эффективно назначать задачи, контролировать сроки, видеть движение средств, координировать персонал и понимать что происходит в компании. Сервис отлично подходит для малого бизнеса и активных команд, где важны скорость, дисциплина и порядок. Руководитель получает больше контроля, а команда работает слаженно и быстрее достигает результата.

  42. MarvinCot's avatar MarvinCot says:

    overseas pharmacy no prescription Online medicine order medicine online order

  43. Если бизнес растет, manage top система позволяет устранить хаос в рабочих задачах, документообороте и рабочем взаимодействии между подразделениями. Система объединяет ключевые процессы в одной системе, чтобы руководитель видел реальную картину по команде, поручениям, согласованиям и финансам без ручных таблиц. Это практичный вариант для компаний, которым необходимы контроль, прозрачность работы и развитие бизнеса без лишней рутины и лишних задержек каждый день.

  44. Thomasdar's avatar Thomasdar says:

    certified canadian pharmacy: SteadyMeds pharmacy – SteadyMeds

  45. Thomasdar's avatar Thomasdar says:

    canadian drugs: SteadyMeds – SteadyMeds

  46. MichaelDenda's avatar MichaelDenda says:

    http://steadymedspharmacy.com/# canadian pharmacy ltd

  47. Hi to every , for the reason that I am really eager of reading this weblog’s post to be updated daily. It carries pleasant stuff.

Leave a Reply

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