What is web API in ASP.NET?
Before knowing what is web API firstly we should know about API. Well, it stands for Application programming interface which is a set of subroutine definitions, protocols, and tools for building software and applications.
To understand in simple words API is like an interface that is a set of functions and methods which allow programmers to access its specific features and data of an application.
Web API is accessed using HTTP protocols
We can build it using many different technologies like Java, .NET, etc. In .NET it also builds API with vb.net, c#.net and core asp.net.
For example, Twitter’s APIs provide programmatic access to read and write data, and using it we can integrate its capabilities into your application.
ASP.NET API Web API
The ASP.NET Web API is a framework for building HTTP based services which will be accessed in several applications on different platforms like web, windows, mobile, etc.
It works more or less an equivalent way as an ASP.NET MVC web application except that it sends data as a response rather than an HTML view. It is the same as a web service or WCF service but the exception is that it only supports HTTP protocol.
Features of Asp.Net Web API
It supports different MVC features like controllers, routing, model binders, action results, filter, IOC container, or dependency injection that makes it simpler and easier to develop.
We can create Asp.net web API which is formatted by Web API’s MediaTypeFormatter in XML or JSON or any other format which you want to add as MediaTypeFormatter. It supports convention-based Create, Update, and Delete Actions from when it works with HTTP verbs like GET, POST, PUT and DELETE.
We can create WebAPI in different ways which are accepted and generate content which not be object-oriented like the image or any other document files. The Asp.Net Web API gives responses in the HTTP status code. Well, it can be hosted in the application or on IIS.
ASP.NET Web API has automatic support for OData. Thus, we can place the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
When to choose ASP.NET Web API?
-
- If you want to build a service that supports only the HTTP protocol.
- For building RESTful HTTP based services.
- If you are familiar with ASP.NET MVC.
- If you are using .NET Framework 4.0 or above that time you choose to use Asp.Net Web API.
Advantages of Asp.Net Web API
-
- If you want to create a good experience for the users of your website regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site then you need to use Ajax.
- ASP.NET web API allows us to create applications that can be called via AJAX.
- Nowadays, we want to have our application for mobile devices like iPad, android, windows. Also, it is very important that our application should be a different platform’s browsers.
- It is a framework, which helps us to create a service that is compatible with all browsers.
- It is a great framework, which allows display data and service to different devices.
- ASP.NET Web API is an open-source platform to make REST full services on the .NET Framework.
Advanced Architecture for ASP.NET Core Web API
Building a more perfect API depends on good architecture. There is much planning and thought behind this architecture, so let’s get started. Architecture have three layers which is listed below.
- API Layer
- Domain Layer
- Data Layer
Now let’s understand that lays in detail.
API Layer
- API Layer is the final layer of Architecture. This layer contains the code for Web API last logic including controllers.
- The API project for the solution will have a single responsibility, and that is only to handle the HTTP requests received by the web server and to return the HTTP responses with either success or failure. There will be very minimal business logic in this project. We will handle exceptions and errors that have occurred within the Domain or Data projects to effectively communicate with the buyer of APIs. This communication will use HTTP response codes and any data to be returned located in the HTTP response body.
- In ASP.NET Core 2.0 Web API, routing is done using Attribute Routing. If you would like to find out more about Attribute Routing in ASP.NET Core go here. We are also using dependency injection to have the Supervisor assigned to each Controller. Every Controller’s Action method features a corresponding Supervisor method which will handle the logic for the API call. We have a segmented the Album Controller below to point out these concepts.
Domain Layer
First of all, we need to explain how we build out the contracts through interfaces and the implementations for our API business logic. Let’s look at the Domain layer. The Domain layer has the following functions:
- Defines the Entities objects that will be used throughout the solution. These models will represent the Data layer’s data models.
- It defines the View Models which will be utilized by the API layer for HTTP requests and feedbacks as single objects or regulates objects.
- Defines the interfaces using which our Data layer can implement the data access logic.
- Implements the Supervisor which will contain methods called from the API layer. Each method will represent an API call and can convert data from the injected Data layer to View Models to be returned.
- Our Domain Entity objects are a characteristic of the database that we are using to reserve and recover data used for the API business logic. Every entity object will contain the properties represented in our case the SQL table. An example is the EmployeeData entity.
Code sample is below.
public sealed class EmployeeData
{
public int Id { get; set; }
public string Name { get; set; }
public int City { get; set; }
public ICollection<Track> Tracks { get; set; } = new HashSet<Track>();
public Age Age { get; set; }
}
The EmployeeData table in the SQL database has three columns: Id, Name, and City. These three properties are part of the EmployeeData entity as well as the Employee’s Age, a collection of associated Tracks and the associated Employees. As we will see in the other layers in the API architecture, we will build upon this entity object’s definition for the ViewModels in the project.
The ViewModels help give more information for the consumer of the APIs. Let’s look at the EmployeeData ViewModel. It is very similar to the EmployeeData Entity but with an additional property. In the design of API, we determined that each Employee should have the Age in the payload passed back from the API. This will allow the API consumer to have that crucial piece of information about the Employee without having to have the EmployeeData View Model passed back in the payload (especially when we are sending back a large set of Employees). An example of our EmployeeDataViewModel is below.
public class EmployeeDataViewModel
{
public int Id {get; set;}
public string Name {get; set;}
public int City {get; set;}
public EmployeeDataViewModel Employee {get; set;}
public IList<TrackViewModel> Tracks {get; set;}
}
As shown in the above example, the interface defines the methods needed to implement the data access methods for the EmployeeData entity. Each entity object and interface are well defined and simplistic that allows the next layer to be well defined.
Data Layer
The next layer of the API architecture is the Data Layer. In example solution, used Entity Framework Core 2.0. This will mean that we have the Entity Framework Core’s DBContext defined but also the Data Models generated for each entity in the SQL database.
While you can have a multitude of Data Layer implementations, just remember that it must adhere to the requirements documented on the Domain Layer; each Data Layer implementation must work this is done using Dependency Injection (as we discussed earlier) for each of the repository objects we implement. Here we have discussed how we use Dependency Injection and the code when we look at the API Layer. Key to the Data Layer is the implementation of each entity repository using the interfaces developed in a Domain Layer. Looking at the Domain Layer’s Album repository as an ex shows that it implements the IAlbumRepository interface. Each repository will connect the DBContext this will allow for access to the SQL database using Entity Framework Core.
public class EmployeeRepository : IEmployeeRepository
{
private readonly EmployeeContext _context;
public EmployeeRepository(EmployeeContext context)
{
_context = context;
}
private async Task<bool> EmployeeExists(int id, CancellationToken ct = default(CancellationToken))
{
return await GetByIdAsync(id, ct) != null;
}
public void Dispose()
{
_context.Dispose();
}
public async Task<List<EmployeeData>> GetAllAsync(CancellationToken ct = default(CancellationToken))
{
return await _context.EmployeeData.ToListAsync(ct);
}
public async Task< EmployeeData > GetByIdAsync(int id, CancellationToken ct = default(CancellationToken))
{
return await _context. EmployeeData.FindAsync(id);
}
public async Task< EmployeeData > AddAsync(EmployeeData newemp, CancellationToken ct = default(CancellationToken))
{
_context. EmployeeData.Add(newemp);
await _context.SaveChangesAsync(ct);
return newemp;
}
public async Task<bool> UpdateAsync(EmployeeData EmployeeData, CancellationToken ct = default(CancellationToken))
{
if (!await EmployeeExists(employee.Empid, ct))
return false;
_context. EmployeeData.Update(employee);
_context.Update(employee);
await _context.SaveChangesAsync(ct);
return true;
}
public async Task<bool> DeleteAsync(int id, CancellationToken ct = default(CancellationToken))
{
if (!await EmployeeExists(id, ct))
return false;
var toRemove = _context. EmployeeData.Find(id);
_context. EmployeeData.Remove(toRemove);
await _context.SaveChangesAsync(ct);
return true;
}
}
Using the Data Layer encapsulating all data access will allow facilitating a better testing story for your API. We can build multiple data access implementations: one for SQL database storage, another for maybe a cloud NoSQL storage model and finally a mock storage implementation for the unit tests in the solution.
Conclusion
In this blog you can understand architecture of Asp.Net core API. By using API, ASP.NET Core Software Company can build cross platform services. Using API, you can use its service for build different platform application and same business logic in every platform application. Its advanced architecture includes all three layers to work first one is Domain Layer second is API layer and third is data layer all layers are work on different things.