Back to: ASP.NET Core Web API Tutorials
Introduction to ASP.NET Core Web API
In this article, I will briefly introduce the ASP.NET Core Web API Framework. By the end of the article, you will understand the following pointers.
- Why Do We Need Web API?
- What is Web API?
- What is ASP.NET Core Web API?
- Why We Need ASP.NET Core Web API?
- What is Rest?
- What are the REST Principles?
- Difference Between ASP.NET Web API and ASP.NET Core Web API
Why Do We Need Web API?
Suppose you have an idea for developing and launching a product. To do this, you need to build a website and launch this product. Then what will you do? You will create a website using any web technologies like ASP.NET MVC, PHP, ASP.NET Core, JSP, etc., that are available on the market. Of course, you will need a database, such as MySQL, Oracle, SQL Server, etc., to store your product’s business data.
So, by combining the website and the database, you will have a fully functional, dynamic website that interacts with the database. Now, after some time, your business grows. Now, along with the website, you also want Android and iOS apps. That means you want three different applications (Website, Android, and iOS) for your business. But remember, you only have one database in the backend, which stores all the business data. So, we have three different applications and one database. So, all three applications have to interact with the same database, as shown in the image below.
If all three applications interact directly with the database, we have some problems. Let us understand the issues first, and then we will see how to overcome the above problems.
Problems:
- Duplicate logic for each Application: The business should have some business logic. We will write the same logic for each application type, which means repeating the same logic for each type of application. This will duplicate our code.
- Error-Prone Code: The business logic is written for each type of application. We have to write the code in three different applications in our example. So, you might miss some code or logic in some applications. This will add more errors to your application.
- Some Front-end frameworks cannot communicate directly with the Database: If you are developing the website (i.e., front-end) using the angular framework, then the angular framework cannot communicate directly with the database. Angular is a front-end framework.
- Hard to Maintain: This type of structure is hard to maintain. We have written the code in many places, and if we want to improve our application, we need to do the same thing in many places.
There are also many other problems that we face in this structure. Let’s see how to overcome the above issues, or we can say why we need Web APIs.
Need for Web APIs:
As you can see in the image below, we have three applications on the left and the database on the right.
We aim to establish communication between all these three applications and the database to manage the data. So, what will we do? We will add a new Web API Project between these three front-end applications and the back-end database. This Web API Project will interact with the database, and all three applications will only interact with the Web API Project, as shown in the image below.
So, the Website, Android, and iOS applications do not have direct access to the database. They only need to communicate with the Web API Project, and it is the Web API project’s responsibility to interact with the database. The entire business logic will be written in the Web API project only, so we need Web API for our project. So, Web API acts as a mediator between the Front-End and Back-End.
Advantages of Web API:
The advantages of using Web APIs are as follows:
- Platform Independence: Web APIs can be consumed by any client that understands standard web protocols like HTTP, regardless of the underlying programming language.
- Low Bandwidth: APIs typically exchange data using JSON or XML, which is much lighter than full HTML views, reducing the amount of data transmitted.
- Reusability: APIs promote code reuse. Once an API is defined and implemented, it can be used by multiple clients or applications without requiring significant changes. That means we write the logic in one place, i.e., in our Web API project, and all applications will use the same logic.
- Security: APIs can be secured using authentication and authorization mechanisms, ensuring that only Authenticated and authorized clients can access sensitive data or perform specific actions.
- Extend Application Functionality: Suppose, first, we develop the website. Then, we can extend and develop an Android App. Again, in the future, if you want to add another type of application, such as iOS, we don’t have to write any logic.
What is Web API?
A Web API, or Web Application Programming Interface, is a set of rules and protocols allowing different software applications to communicate over the Internet in a distributed environment. It defines the methods and data formats that applications can use to request and exchange information. Web APIs are typically based on HTTP (Hypertext Transfer Protocol) and can return data in various formats, such as JSON, XML, or others.
Web APIs typically expose a set of endpoints, which are URIs that different clients, such as web, mobile, or desktop, can call to perform specific operations, such as retrieving or submitting data. For example, A weather service API might expose the following endpoints:
- GET /weather/today?location=Mumbai – Retrieves today’s weather for Mumbai.
- GET /weather/forecast?location=Mumbai&days=5 – Retrieves a 5-day weather forecast for Mumbai.
What is ASP.NET Core Web API?
ASP.NET Core Web API is a framework provided by Microsoft for building HTTP-based APIs (RESTful web services) using ASP.NET Core. According to Microsoft, the ASP.NET Core Web API is ideal for building Restful services on the .NET Platform. These Web API services can then be consumed by a variety of clients, such as
- Browsers
- Mobile applications
- Desktop applications
- IOTs, etc.
Why We Need ASP.NET Core Web API?
Nowadays, a web application is not sufficient to reach all its customers. People are becoming very smart; they use different types of devices, such as mobile phones, iPhones, tablets, etc., daily. These devices have many apps that make their lives easy. In simple words, we can say that we are moving toward the app world from the web.
So, if you want to expose your data (business data) to browsers and modern devices quickly, securely, and easily, then you should have an API that must be compatible with browsers and all these modern devices.
The ASP.NET Core Web API is an excellent framework for building HTTP services that can be consumed by a broad range of clients, including browsers, mobiles, iPhones, and tablets. ASP.NET Core Web API provides several benefits:
- Performance: ASP.NET Core is known for its high performance and scalability, making it suitable for building high-traffic APIs. It is faster than its predecessor, ASP.NET.
- Cross-platform: ASP.NET Core runs on Windows, Linux, and macOS, allowing developers to deploy their APIs on different operating systems.
- Modularity: The framework is built with modularity in mind, allowing developers to include only the necessary components, which keeps the application light and responsive.
- Modern Features: It supports modern web development features like dependency injection, middleware, and asynchronous programming.
- Security: It includes built-in features for securing APIs, such as authentication and authorization mechanisms.
What is Rest?
REST (stands for Representational State Transfer) is an Architectural Design Pattern used for Exchanging Data over a Distributed Environment. With Rest, there is something called a Client and a Server, and the data will be exchanged between the client and server over a distributed environment. A Distributed Environment means the client can be on any platform like Java, .NET, PHP, etc.; the server can also be on any platform like Java, .NET, PHP, etc.
The REST Architectural Pattern treats Each Service as a Resource, and a client can consume these resources (perform CRUD Operations) by using HTTP Protocol Methods (GET, POST, PUT, DELETE) and URIs. For example, a RESTful API for a book management system might include endpoints like:
- GET /books – Retrieves a list of books.
- GET /books/{id} – Retrieves details of a specific book.
- POST /books – Adds a new book.
- PUT /books/{id} – Updates details of a specific book.
- DELETE /books/{id} – Deletes a specific book.
What are the REST Principles?
The REST architectural pattern specifies a set of constraints that a system should adhere to. Let us proceed and understand the REST constraints or principles.
Client-Server Architecture:
A RESTful system must have a clear separation of concerns between the client (responsible for the user interface) and the server (responsible for data storage, processing, and application logic). The client and server communicate through a standardized interface (usually HTTP).
Why It Matters:
- It allows both client-side and server-side components to be developed and deployed independently.
- Changes in the client’s UI do not require changes in the server’s architecture, and vice versa.
Example: On a social media platform, a mobile app (client) sends requests such as GET /users/{userId} to retrieve a user profile or POST /posts to create a new post. The server handles these requests and returns the appropriate data, ensuring the client’s responsibilities (UI) and the server’s responsibilities (logic, data handling) remain separate.
Stateless:
The stateless constraint specifies that client-server communication must be stateless between requests. That means the server should not store any information, i.e., session state related to the client on the server. Each request from the client to the server must contain all the necessary information so that the server can identify the client and process that request.
Why It Matters:
- Any server can handle any request because there is no client-specific context stored on the server.
- Each request from the clients can be treated independently by the server.
Example: A request such as GET /users/456 might include an authentication token in the header (Authorization: Bearer <token>). Because the server relies solely on the current request’s data, it can verify the token, fetch the user details, and respond—all without referencing any previous interactions.
Cacheable:
In real-time applications, some data provided by the server is not changed that frequently, like the list of Countries, States, Cities, Products, etc. RESTful APIs can take advantage of HTTP caching mechanisms. Responses from the server should indicate whether a resource is cacheable by the client and, if so, for how long. Caching improves performance and reduces server load by allowing clients (and intermediaries) to reuse responses.
Why It Matters:
- Frequently requested resources can be served from a cache instead of re-fetching from the server.
- Reduces the number of round trips to the server.
Example: If a client requests a product details resource, e.g., GET /products/123, the server’s response might include HTTP caching headers such as Cache-Control: max-age=3600 or Expires: <date>. These headers tell the client how long it can reuse the response before requesting a fresh copy from the server. So, subsequent requests for the same resource can be served from the client’s cache, reducing the need to fetch data from the server again until the cache expires or is invalidated.
Uniform Interface:
The Uniform Interface is often considered the most critical REST constraint. It ensures that all clients can communicate in a standardized way. It is typically broken down into four sub-constraints:
- Resource Identification: Each resource (such as a user, order, or product) is uniquely identifiable by a URI (Uniform Resource Identifier). For example, in a blog platform, each post can be accessed at https://example.com/posts/{postId}.
- HTTP Methods: Resources are manipulated by sending representations (e.g., JSON, XML) to the server, typically using standard HTTP methods (GET, POST, PUT, DELETE).
- Self-Descriptive Messages: Each message contains enough information to describe how to process the request. This includes using the appropriate HTTP method, headers, and media types to convey the intention and format of the request or response.
- Hypermedia as the Engine of Application State (HATEOAS): HATEOAS encourages a more dynamic interaction with the API by informing clients of other actions available from the current resource. Hyperlinks, embedded in responses, guide the client on what operations are possible next.
Why It Matters:
- Clients interact with resources in the same way.
- Changes in the server’s internal logic do not necessarily break clients, as they adhere to a uniform protocol.
Examples:
- GET /books retrieves a list of books.
- GET /books/123 retrieves a book with ID 123.
- POST /books create a new book.
- PUT /books/123 updates the book with ID 123.
- DELETE /books/123 deletes the book with ID 123.
Content Negotiation:
Clients and servers can negotiate the media type used to represent a resource. The client typically specifies its preferred format via the Accept header, and the server responds in one of the requested formats if supported.
Why It Matters:
- Allows different clients (mobile apps, browsers, etc.) to request the format they can best handle (JSON, XML, HTML, etc.).
- Servers can support multiple formats without changing the resource identifier.
Example: If a client requests an article by calling GET /articles/456 and includes Accept: application/json, the server can respond with JSON (e.g., Content-Type: application/json). If the client had requested Accept: application/xml, the server could respond with XML if it supports it.
Layered System:
A RESTful service can be composed of multiple layers, such as security, caching, load balancing, and data storage. Each layer is unaware of the other layers except for the one it directly interacts with, i.e., Each layer only knows about the layer immediately above and below it.
Why It Matters:
- Services can grow by adding new layers (e.g., caching or authentication) without breaking existing clients.
- Intermediary layers can handle tasks like load balancing, SSL termination, logging, or filtering malicious requests.
Example:
An e-commerce application may have:
- A Web Server (Layer 1) that receives requests, handles routing, and then communicates with
- An Application Layer (Layer 2) for business logic, which in turn communicates with
- A Database Layer (Layer 3).
The client only knows it sends requests to the web server; it does not need to know the details of how the application or database layers work.
Code on Demand (Optional)
A RESTful service can optionally provide executable code, such as JavaScript, that the client can run, extending its functionality on the fly. This is an optional constraint and is used to add flexibility to the client.
For example, a server might return a piece of JavaScript that includes filtering or sorting logic for a dataset. The client can execute this code locally to handle certain user interactions without making additional requests to the server, improving performance and user experience.
Difference Between ASP.NET Web API and ASP.NET Core Web API
ASP.NET Web API and ASP.NET Core Web API represent two different approaches to building Web APIs (Restful Services) within the ASP.NET framework, with several key distinctions:
Platform Support:
- ASP.NET Web API: It is built on the .NET Framework, which means it runs only on Windows operating systems.
- ASP.NET Core Web API: It is part of the ASP.NET Core framework, which runs on .NET Core. This allows it to be cross-platform, operating on Windows, Linux, and macOS.
Performance
- ASP.NET Web API: While efficient, it does not match the performance improvements that have been realized in ASP.NET Core, mainly due to the older architecture and its dependence on the .NET Framework.
- ASP.NET Core Web API: Designed to be lightweight and high-performance. ASP.NET Core has been optimized from the ground up to be faster and more modular. It can handle more requests per second and uses fewer resources because of its ability to support asynchronous programming more extensively.
API Design Features
- ASP.NET Web API: Supports RESTful services but does not have native support for features like versioning and response compression without additional packages or libraries.
- ASP.NET Core Web API: Includes built-in support for advanced API design features, such as API versioning, response caching, and response compression, making it easier to build robust APIs.
Configuration and Hosting
- ASP.NET Web API: Typically hosted in IIS (Internet Information Services), it heavily relies on system configuration through web.config files for application settings.
- ASP.NET Core Web API: Offers more flexibility in hosting options. It can be hosted in IIS, Kestrel (a cross-platform web server built for ASP.NET Core), or Docker containers. Configuration can be achieved through various sources like JSON files, environment variables, command-line arguments, etc., without relying on web.config.
Dependency Injection
- ASP.NET Web API: Supports dependency injection but is not built into the framework. Developers often need to use third-party libraries like Unity or Ninject to achieve dependency injection.
- ASP.NET Core Web API: The ASP.NET Core framework has built-in dependency injection support, promoting more loosely coupled code and better manageability.
Middleware Support
- ASP.NET Web API: This does not have middleware support the way ASP.NET Core does. Custom handlers and modules can be created, but they are generally more complex to implement and integrate.
- ASP.NET Core Web API: Uses a middleware pipeline that is easy to customize and configure. Middleware components can be used to execute code before and after your application handles a request, enabling scenarios like authentication, error handling, and logging with less complexity.
Choosing Between ASP.NET Web API and ASP.NET Core Web API:
- Platform Requirements: If you need cross-platform compatibility or want to deploy on Linux or macOS, ASP.NET Core Web API is the better choice.
- Performance: For applications requiring high performance and scalability, ASP.NET Core Web API is generally preferred due to its lightweight nature and optimized performance.
In the next article, I will discuss HTTP (Hyper Text Transport Protocol), i.e., HTTP Verbs or Methods, HTTP Status Codes, HTTP Requests, and Responses. Here, in this article, I try to give a brief introduction to the ASP.NET Core Web API Framework. I hope you enjoy this Introduction to ASP.NET Core Web API article.
Thank u very much , this article was very helpful to me
Thank you so much
Very nice tutorials
This was very helpful
Thank you ! Amazing work.
ty