.NET Core REST API to Get/Post/Put/Delete Calls

Vaibhav Bhapkar
5 min readJul 31, 2020

In this article, We will explore REST API Calls in .NET Core,

1) Get List of resources

For creating REST API methods we are creating a controller that derives from the ControllerBase class.

On thing over here when you are working with a web API project derive your controller class from ControllerBase only and not from Controller as Controller adds support for view object So class derived from the controller when working with and MVC web application.

Let's see an example of retrieving the product list,

ProductController.cs

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using EmployeeManagement.API.Model;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace EmployeeManagement.API.Controllers{[Route(“api/[controller]”)][ApiController]public class ProductController : ControllerBase{private readonly IProductRepository productRepository;public ProductController(IProductRepository productRepository){this.productRepository = productRepository;}[HttpGet]Public async Task<ActionResult> GetProducts(){return Ok(await productRepository.GetProducts());}}}

As you have seen over here we injected the created repository in our controller class to fetch required data here we defined the method which will return a list of products with status ok with status code 200.

Get Call

Some of the common HTTP Status Code listed below,

Level 200200- OK201 –Created204- No contentLevel 400400 — Bad request401 –Unauthorized404 — Not FoundLevel 500500 — Internal Server Error501 — Not implemented503 –Service unavailable

2) Get Resource with id

As we have seen earlier we are getting a list of product with endpoint api/product so if we want to get a product with id the endpoint will be api/product/{id}

Let’s look below code for example,

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using EmployeeManagement.API.Model;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace EmployeeManagement.API.Controllers{[Route(“api/[controller]”)][ApiController]public class ProductController : ControllerBase{private readonly IProductRepository productRepository;public ProductController(IProductRepository productRepository){this.productRepository = productRepository;}[HttpGet]public async Task<ActionResult> GetProducts(){return Ok(await productRepository.GetProducts());}[HttpGet(“id:int”)]public async Task<ActionResult<Product>> GetProduct(int id){try{var result = await productRepository.GetProduct(id);if (result == null){return NotFound();}return result;}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError, “Error retrieving data from datatbase”);}}}}

As you noticed we decorated this method also with the HTTPGet and extended the route with the id parameter to get only requested and also added HTTP constraint that parameter should be of integer type.

Get Call

3) POST in REST API to add product

For the post request, we are passing the product object to the endpoint. To make your model binding work we need to declare our controller as APIController or make your method parameter as FromBody attribute. If you are not following then you model binding will not work.let's check the example below,

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using EmployeeManagement.API.Model;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace EmployeeManagement.API.Controllers{[Route(“api/[controller]”)][ApiController]public class ProductController : ControllerBase{private readonly IProductRepository productRepository;public ProductController(IProductRepository productRepository){this.productRepository = productRepository;}[HttpGet]public async Task<ActionResult> GetProducts(){return Ok(await productRepository.GetProducts());}[HttpGet(“{id:int}”)]public async Task<ActionResult<Product>> GetProduct(int id){try{var result = await productRepository.GetProduct(id);if (result == null){return NotFound();}return result;}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError, “Error retrieving data from datatbase”);}}public async Task<ActionResult<Product>> CreateProduct(Product product){try{if (product == null){return BadRequest();}var result = await productRepository.AddProduct(product);return CreatedAtAction(nameof(GetProduct),new { id=result.productId},result);}catch(Exception){return StatusCode(StatusCodes.Status500InternalServerError, “Bad Request”);}}}}

As you see in this example we used CreateAtAction method to return created object its status code and location URI was the created object exists in response header please check the response shown below,

Post Call

4) Model validation in .NET Core Rest API

Required attribute — This attribute specifies the field is required

Range attribute — Specifies the minimum and maximum allowed value

MinLength & MaxLength attribute: specifies the minimum and maximum length of string

Compare attribute — Compare two properties of the model(password & confirm password)

Regular Expression — Check the value matches the pattern specified by RE.

5) PUT in REST API

We will see how we can update existing resources with put requests. Let's take an example of updating product,

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using EmployeeManagement.API.Model;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace EmployeeManagement.API.Controllers{[Route(“api/[controller]”)][ApiController]public class ProductController : ControllerBase{private readonly IProductRepository productRepository;public ProductController(IProductRepository productRepository){this.productRepository = productRepository;}[HttpGet]public async Task<ActionResult> GetProducts(){return Ok(await productRepository.GetProducts());}[HttpGet(“{id:int}”)]public async Task<ActionResult<Product>> GetProduct(int id){try{var result = await productRepository.GetProduct(id);if (result == null){return NotFound();}return result;}catch (Exception){return StatusCode(StatusCodes.Status500InternalServerError, “Error retrieving data from datatbase”);}}[HttpPut(“{id:int}”)]public async Task<ActionResult<Product>> UpdateProduct(int id,Product product){try{if(id!=product.productId){return BadRequest(“Product id mismatch”);}var producttoupdate = await productRepository.GetProduct(id);if(producttoupdate == null){return NotFound(“Product not found”);}var result = await productRepository.UpdateProduct(product);return result;}catch(Exception){return StatusCode(StatusCodes.Status500InternalServerError, “Bad Request”);}}}}

Result:

PUT Call

6) DELETE in REST API

Let's check an example of deleting of product,

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using EmployeeManagement.API.Model;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace EmployeeManagement.API.Controllers{[Route(“api/[controller]”)][ApiController]public class ProductController : ControllerBase{private readonly IProductRepository productRepository;public ProductController(IProductRepository productRepository){this.productRepository = productRepository;}[HttpDelete(“{id:int}”)]public void DeleteProduct(int id){productRepository.DeleteProduct(id);}}}

Result:

Delete Call

Thank You, See you in the next article !!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

--

--

Vaibhav Bhapkar

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *