Loading, please wait...

A to Z Full Forms and Acronyms

Get list of resources using ASP.NET Core REST API and by ID.

In this article we will learnCreating a REST API using ASP.NET CoreReturn a list of resources i.e a list of employees from the REST APITo retrieve a resource by id. For example, retrieve Employee by Id.

Get the list of resources using ASP.NET Core REST API

Make REST API utilizing ASP.NET Core

To make a REST API utilizing ASP.NET center, make a controller class that gets from the inherent ControllerBase class. ControllerBase is in Microsoft.AspNetCore.MVC namespace.

Controller versus ControllerBase in ASP.NET Core

On the off chance that you are making a REST API, make your Controller class get from ControllerBase and not Controller class. The controller gets from ControllerBase and includes support for MVC sees.

 

To make a controller that gets from the Controller class in the event that you are building an MVC web application. Then again, on the off chance that you are making a Web API, make a controller class that gets from the ControllerBase class. So to put it plainly, the Controller is for MVC web applications and ControllerBase is for MVC Web APIs.

In the event that you are intending to utilize the controller both for a web application and for a web API, at that point get it from the Controller class.

ASP.NET Core API Controller Example

EmployeesController is an API Controller so design it with [ApiController] quality

As the name suggests, the [Route] quality determines the course. The word [controller] in square sections determines we simply utilize the name of the Controller in the URL to get the EmployeesController.  IEmployeeRepository is infused into the Controller class utilizing the standard constructor infusion. It is this IEmployeeRepository that recovers representative information from the fundamental SQL Server database. We actualized this vault class in our past recordings in this arrangement.

[HttpGet] quality determines that this technique ought to react to the HTTP GET demands.

The arrival sort of Task<ActionResult> permits us to return status code 200 OK alongside the rundown of representatives or status code 500 if there is a worker blunder recovering information from the database.

using EmployeeManagement.Api.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace EmployeeManagement.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeesController : ControllerBase
    {
        private readonly IEmployeeRepository employeeRepository;

        public EmployeesController(IEmployeeRepository employeeRepository)
        {
            this.employeeRepository = employeeRepository;
        }

        [HttpGet]
        public async Task<ActionResult> GetEmployees()
        {
            try
            {
                return Ok(await employeeRepository.GetEmployees());
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, 
					"Error retrieving data from the database");
            }
        }
    }
}

Http Status codes

Gives the guest i.e the customer of the API knows the status of the solicitation. A portion of the normal status codes are 200/OK, 404/Not Found, 204/No Content. For the total rundown of HTTP status codes and what they mean, it would be ideal if you visit https://en.wikipedia.org/wiki/List_of_HTTP_status_codes.

ASP.NET center gives the accompanying partner techniques to return HTTP Status Codes.

ASP.NET Core REST API get by id

REST API URLs

A GET request to the URI/api/workers restores the rundown of Employees

A GET request to the URI/api/workers/1 should restore the Employee whose ID is 1

ASP.NET Core REST API Get by Id Example

using EmployeeManagement.Api.Models;
using EmployeeManagement.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EmployeeManagement.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeesController : ControllerBase
    {
        private readonly IEmployeeRepository employeeRepository;

        public EmployeesController(IEmployeeRepository employeeRepository)
        {
            this.employeeRepository = employeeRepository;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()
        {
            try
            {
                return (await employeeRepository.GetEmployees()).ToList();
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError,
                    "Error retrieving data from the database");
            }
        }

        [HttpGet("{id:int}")]
        public async Task<ActionResult<Employee>> GetEmployee(int id)
        {
            try
            {
                var result = await employeeRepository.GetEmployee(id);

                if (result == null) return NotFound();

                return result;
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError,
                    "Error retrieving data from the database");
            }
        }
    }
}

A strategy finished with the HttpGet quality determines that technique should deal with HTTP GET request. Both GetEmployees() and GetEmployee() are embellished with the HttpGet characteristic. The thing that matters is, HttpGet characteristic on GetEmployee() strategy additionally has a course format. The id of the worker will be affixed to the URL/api/employees.

[HttpGet("{id:int}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)

So on the off chance that the URL is/api/representatives then it is dealt with by GetEmployees() strategy. On the off chance that the URL is/api/workers/1 then it is dealt with by GetEmployee(int id) strategy.

The worker id esteem in the URL is naturally planned to the id boundary on the GetEmployee(int id) strategy.

As we are utilizing the int course requirement on the id course boundary, the id esteem in the URL is planned to the technique boundary, just if the worth is a whole number.

The representative id is then passed to employeeRepository.GetEmployee(id) technique that recovers the individual worker from the database.

In the event that the representative is found, ASP.NET Core naturally serializes the worker article to JSON and composes it into the reaction body. This reaction body alongside the http status code 200 OK is come back to the customer. On the off chance that the representative isn't discovered, at that point http status code 404 NotFound is returned.

A to Z Full Forms and Acronyms

Related Article

ADVERTISEMENT
ADVERTISEMENT