Web Api Extra
Web Api Extra
1. They should have [ApiController] attribute on them. This attribute tells that the controller will server
HTTP API Responses.
-----------------------------------------------------------------------------------------------------------------
sysntax:-
[ApiController]
[Route("someURL/[controller]")]
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.
-------------------------------------------------------------------------------------------------------------------
systax:-
[ApiController]
[Route("api/[controller]")]
...
The ControllerBase class provides many properties and methods that are useful for handling HTTP
requests. Some of these are:
Name Description
-------------------------------------------------------------------------------------------------------------------
The Web API controller must be applied with [ApiController] attribute so that they can perform API
specific behaviors. These behaviors are:
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 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.
Inside the Models folder, add a class called Reservation.cs to it. The class code is given below:
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.
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 Repository()
new List<Reservations> {
if (reservation.Id == 0)
{
reservation.Id = key;
items[reservation.Id] = reservation;
return 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:
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;
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IRepository, Repository>();
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.
return View();
using APIControllers.Models;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
namespace APIControllers.Controllers
[ApiController]
[Route("api/[controller]")]
[HttpGet]
if (id == 0)
return Ok(repository[id]);
[HttpPost]
repository.AddReservation(new Reservations
Name = res.Name,
StartLocation = res.StartLocation,
EndLocation = res.EndLocation
});
[HttpPut]
[HttpDelete("{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.
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]")]
...
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]
As you can see this method returns all the reservations so you get the JSON of the reservations on the
browser.
IMP :-
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"}
[HttpGet("{id}")]
if (id == 0)
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
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"}
]