0% found this document useful (0 votes)
32 views

Web Api Extra

The document describes how to create web APIs in ASP.NET Core. It explains that API controllers should have the [ApiController] attribute, derive from ControllerBase instead of Controller, and have attribute routing applied. It also discusses what a web API is and how the HTTP verbs like GET, POST, PUT, and DELETE are used to transfer data in JSON or XML formats.

Uploaded by

Rupesh Phalne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Web Api Extra

The document describes how to create web APIs in ASP.NET Core. It explains that API controllers should have the [ApiController] attribute, derive from ControllerBase instead of Controller, and have attribute routing applied. It also discusses what a web API is and how the HTTP verbs like GET, POST, PUT, and DELETE are used to transfer data in JSON or XML formats.

Uploaded by

Rupesh Phalne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Creating Web APIs in ASP.NET Core is very straightforward.

You create controllers that have 3 things:

1. They should have [ApiController] attribute on them. This attribute tells that the controller will server
HTTP API Responses.

2. They should derive from ControllerBase class instead of Controller class.

3. They should have attribute routing applied on them like [Route("someUrl/[controller]")].

-----------------------------------------------------------------------------------------------------------------

The controller of a Web API looks like:

sysntax:-

[ApiController]

[Route("someURL/[controller]")]

public class ExampleController : ControllerBase

What is Web API?

A Web API is an API which can be accessed over the web using HTTP Protocol.

For example, we can get the current stock value of any organization right in our browser by calling any
Stock Market Web API. A Web API can be built in any technology like ASP.NET Core, JAVA, Python, etc. It
can also be consumed in any technology.

This makes Web APIs a perfect choice for apps, build on different technologies, to communicate with
one another.

The work of the Web API is to transfer data over the internet.

The data is transferred with the HTTP Protocol’s Request methods which are commonly known as HTTP
Verbs.

The mostly used HTTP Verbs are GET, POST, PUT, DELETE.

JSON and XML file formats are used by Web APIS to transmit data over the internet.

-------------------------------------------------------------------------------------------------------------------

“ControllerBase” vs “Controller” class


You must not create a Web API controller by deriving from the Controller class. This is because the
Controller class derives from ControllerBase class and adds support for views, so it’s for handling web
pages, not web API requests. There’s an exception to this rule: if you plan to use the same controller for
both views and web APIs, then only derive it from Controller class. Check the skeleton of an ASP.NET
Core Web API which derives from ControllerBase class.

systax:-

[ApiController]

[Route("api/[controller]")]

public class ReservationController : ControllerBase

...

The ControllerBase class provides many properties and methods that are useful for handling HTTP
requests. Some of these are:

Name Description

BadRequest Returns 400 status code.

Ok Returns a 200 status code along with the result object.

NotFound Returns 404 status code.

PhysicalFile Returns a file.

-------------------------------------------------------------------------------------------------------------------

What is an ApiController attribute?

The Web API controller must be applied with [ApiController] attribute so that they can perform API
specific behaviors. These behaviors are:

1. Respond to Attribute Routing.


2. Automatically triggers an HTTP 400 response when resource is not found on the server.

3. Defines the location at which an action method’s parameter value is found. We use [FromBody],
[FromForm], [FromHeader], [FromQuery], [FromRoute] attributes to define these locations.

4. When action method’s parameter is annotated with the [FromForm] attribute then the
multipart/form-data request content type is inferred.

5. Enables Web API returned error to be based on the RFC 7807 specification. This enables Web APIs
made in different technologies like Java, Ruby, ASP.NET Core etc to communicate with one another
without any problem.

demo :-

Create the Example Project

Create a new project in Visual Studio, choose ASP.NET Core Web APP (MVC) template and name it
APIControllers. Select the latest version of the DOT NET framework which is .NET 6.0.

Model & Repository

Inside the Models folder, add a class called Reservation.cs to it. The class code is given below:

public class Reservations

public int Id { get; set; }

public string Name { get; set; }

public string StartLocation { get; set; }

public string EndLocation { get; set; }

Next add a interface file called IRepository.cs to the Models folder and used it to define an interface as
shown in the below code.

public interface IRepository


{

IEnumerable<Reservations> Reservations { get; }

Reservations this[int id] { get; }

Reservations AddReservation(Reservations reservation);

Reservations UpdateReservation(Reservations reservation);

void DeleteReservation(int id);

Finally add a class file called Repository.cs to the Models folder and used it to define a non-persistent store of
reservations. It inherits the IRepository interface we defined earlier.

namespace APIControllers.Models

public class Repository: IRepository

private Dictionary<int, Reservations> items;

public Repository()

items = new Dictionary<int, Reservations>();

new List<Reservations> {

new Reservations {Id=1, Name = "Ankit", StartLocation = "New York", EndLocation="Beijing" },

new Reservations {Id=2, Name = "Bobby", StartLocation = "New Jersey",


EndLocation="Boston" },

new Reservations {Id=3, Name = "Jacky", StartLocation = "London", EndLocation="Paris" }

}.ForEach(r => AddReservation(r));

public Reservations AddReservation(Reservations reservation)

if (reservation.Id == 0)
{

int key = items.Count;

while (items.ContainsKey(key)) { key++; };

reservation.Id = key;

items[reservation.Id] = reservation;

return reservation;

public Reservations this[int id] => items.ContainsKey(id) ? items[id] : null;

public IEnumerable<Reservations> Reservations => items.Values;

public void DeleteReservation(int id) => items.Remove(id);

public Reservations UpdateReservation(Reservations reservation) => AddReservation(reservation);

explanation:-

The Repository class creates 3 set of reservation objects when it is instantiated, and since there is no persistent
storage, any changes will be lost when the application is stopped or restarted.

The Class contains methods and properties to do CRUD Operations and all the reservations are stored in a
Dictionary<int, Reservation> type object. These methods and properties are:

AddReservation – method is used for creating new reservations.


Reservations – property for reading reservation.

UpdateReservation – method is used for updating reservations.

DeleteReservation – method to delete reservations.

next very imp

Configuration in the Program class

We use AddSingleton method to set up the service mapping for the reservation repository. We do this by adding
the below given code line to the Program.cs class.

using APIControllers.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

builder.Services.AddSingleton<IRepository, Repository>();

var app = builder.Build();

Controller for Web API

Now comes the most important part of creating a Controller for the Web API. Remember
that this Controller is just a normal Controller, that allows data in the model to be
retrieved or modified, and then deliver it to the client. It does this without having to use
the actions provided by the regular controllers.
The data delivery is done by following a pattern known by name as REST. REST Stands
for REpresentational State Transfer pattern, which contains 2 things:
1. Action Methods which do specific operations and then deliver some data to the client. These methods are
decorated with attributes that makes them to be invoked only by HTTP requests.

2. URLs which defines operational tasks. These operations can be – sending full or part of a data, adding,
deleting or updating records. In fact it can be anything.

First add the package called Microsoft.AspNetCore.JsonPatch from NuGet. This is needed to support JSON
Patch. I have shown this package in the below image.
Next to the Controllers folder of the project, add a new Controller called ReservationController.cs. Add the
following code to it.

public class ReservationController : Controller

public IActionResult Index()

return View();

now complete code it

using APIControllers.Models;

using Microsoft.AspNetCore.JsonPatch;

using Microsoft.AspNetCore.Mvc;

namespace APIControllers.Controllers

[ApiController]

[Route("api/[controller]")]

public class ReservationController : ControllerBase

private IRepository repository;

public ReservationController(IRepository repo) => repository = repo;

[HttpGet]

public IEnumerable<Reservations> Get() => repository.Reservations;


[HttpGet("{id}")]

public ActionResult<Reservations> Get(int id)

if (id == 0)

return BadRequest("Value must be passed in the request body.");

return Ok(repository[id]);

[HttpPost]

public Reservations Post([FromBody] Reservations res) =>

repository.AddReservation(new Reservations

Name = res.Name,

StartLocation = res.StartLocation,

EndLocation = res.EndLocation

});

[HttpPut]

public Reservations Put([FromForm] Reservations res) => repository.UpdateReservation(res);

[HttpDelete("{id}")]

public void Delete(int id) => repository.DeleteReservation(id);

}
Explanation

Notice the Controller derives from ControllerBase class and has an attribute called [ApiController]
applied to it. The Controller gets the Reservation class object in the constructor through the Dependency
Injection feature.

Route of the API Controller

The route by which this controller can be reached is defined by Attribute Routes. You can check my
tutorial called Learn Attribute Routing in ASP.NET Core to know it in full details.

This Web API Controller is reached through the URL – https://localhost:44324/api/Reservation. Here
“44324” is the port number.

[ApiController]

[Route("api/[controller]")]

public class ReservationController : ControllerBase

...

Now test this thing by running the application and then opening the URL –
https://localhost:44324/api/Reservation on the browser. You will see the JSON of the 3 reservations as
shown in the below image.
explanation:-

The URL calls the Get method of the Reservation controller. This method is shown below:

[HttpGet]

public IEnumerable<Reservation> Get() => repository.Reservations;

As you can see this method returns all the reservations so you get the JSON of the reservations on the
browser.
IMP :-

now do testing for GET METHOD BY APPLYING FOLLOWING URLS

https://localhost:7067/api/Reservation/1

{"id":1,"name":"Ankit","startLocation":"New York","endLocation":"Beijing"}

https://localhost:7067/api/Reservation/2

{"id":2,"name":"Bobby","startLocation":"New Jersey","endLocation":"Boston"}

https://localhost:7067/api/Reservation/3

{"id":3,"name":"Jacky","startLocation":"London","endLocation":"Paris"}

THIS ALL BCZ OF THIS CODE

This action method is shown below.

[HttpGet("{id}")]

public ActionResult<Reservation> Get(int id)

if (id == 0)

return BadRequest("Value must be passed in the request body.");

return Ok(repository[id]);

}
If the client does not sends an id in the request then in that case the id gets the default value of 0. So I
am simply returning BadRequest() for the response.

https://localhost:7067/api/Reservation/0

Value must be passed in the request body.

The HTTP GET requests can be made directly from the browser. Run your application and go to the URL
https://localhost:44324/api/Reservation, where you will see a JSON containing all the reservations, as
shown in the image below:

https://localhost:7067/api/Reservation

[{"id":1,"name":"Ankit","startLocation":"New
York","endLocation":"Beijing"},{"id":2,"name":"Bobby","startLocation":"New
Jersey","endLocation":"Boston"},{"id":3,"name":"Jacky","startLocation":"London","endLocation":"Paris"}
]

You might also like