Introduction to ASP.
NET Core Web API
Why do we need Web APIs?
Suppose you have an idea to develop and launch a product. For this, you need to develop a website
and launch this product. Then what will you do? You will develop a website using any web
technologies like ASP.NET MVC, PHP, ASP.NET Core, JSP, etc., that are available in 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 the entire business data. So, we have three different applications and one database. So,
all these three applications have to interact with the database, as shown in the below image.
If all three applications interact directly with the database, we have some problems. Let us understand
the problems first, and then we will see how to overcome the above problems.
Problems Without Web APIs:
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 has been written in 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 with the database directly. Angular is a front-end framework.
Hard to Maintain: This type of structure is hard to maintain. This is because we have written
the code in so many places, and if we want to improve something in our application, we need
to do the same thing in many places.
There are also lots of other problems that we face in this structure. Let us see how to overcome the
above problems, 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-hand side, and on the right-
hand side, we have the database.
We aim to establish communication between all these three applications and the database. So, what
will we do? We will add a new Web API Project. This Web API Project will interact with the database.
All three applications will only interact with the Web API Project, as shown in the below image.
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,
Web API acts as a mediator between the Front-End and Back-End.
Advantages of Web API:
Using Web API, we can avoid code duplication: We can write the logic in one place, i.e., in
our Web API project, and all applications will use that logic.
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, we don’t have to write any logic.
Abstraction: We have added an extra abstraction layer as we have written all the business
logic in our Web API project. The logic we wrote in the Web API project will not be visible to
the front-end developers.
Security: None of the applications can access the database directly, and hence it provides
security.
What is Web API?
API stands for Application Programming Interface. Web API is a concept (not a technology) that
works on the HTTP Protocol and is used to extend the functionality of an application.
A Web API, or Web Application Programming Interface, is a set of rules and protocols that allows
different software applications to communicate with each other over the internet or a network. It
enables the exchange of data and functionality between various systems, using HTTP (Hypertext
Transfer Protocol) as the communication protocol.
Key Characteristics of Web APIs:
HTTP-Based Communication: Web APIs are designed to work over HTTP, the same
protocol used for Web Browsing. This means APIs can be accessed using standard HTTP
methods like GET, POST, PUT, DELETE, etc. The API endpoints are typically represented as
URLs (Uniform Resource Locators).
Data Exchange Formats: Web APIs use standardized data exchange formats such as JSON
(JavaScript Object Notation) and XML (Extensible Markup Language) to structure and
transmit data between the client and server. JSON has become the most popular format due
to its simplicity and ease of use.
RESTful Architecture: Web APIs are designed to the follow Representational State Transfer
(REST) principles. A RESTful API is stateless, uses standard HTTP methods, and organizes
resources into a hierarchy with unique URLs for each resource.
Authentication and Authorization: Web APIs implement security mechanisms for
authentication and authorization to ensure that only authorized clients can access resources
or perform specific actions. Common authentication methods include API keys, OAuth, and
JWT (JSON Web Tokens).
What is ASP.NET Core Web API?
The term API stands for Application Programming Interface. ASP.NET Core Web API is a framework
provided by Microsoft that makes it easy to build Web APIs, i.e., HTTP-Based Services. The
ASP.NET Core Web API is ideal for building Restful Services (Web Services) on top of the .NET
Platform (.NET Core), commonly known as the .NET Core Platform. These Web API services can
then be consumed by a variety of clients, such as
Browsers (Web Application)
Mobile applications
Desktop applications
IOTs, etc.
ASP.NET Core Web API is commonly used for building RESTful APIs that expose data and services
over HTTP. It’s suitable for various scenarios, including building back-end services for web, mobile,
and desktop applications, providing data to single-page applications (SPAs), and creating
Microservices that can be deployed independently.
Why We Need ASP.NET Core Web API?
Nowadays, a web application is not sufficient or enough to reach all its customers. People are
becoming very smart; they are using different types of devices, such as mobile, iPhones, tablets, etc.,
in their daily lives. These devices have a lot of apps that make their life easy. In simple words, we can
say that we are moving toward the app world from the web.
So, if we want to expose our data (business data) to the browsers and to all these modern device
apps in a fast, secure, and simple way, then we should have an API that should be compatible with
browsers and all these modern devices.
The ASP.NET Core Web API is a great 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 Features:
Below are some of the key features of ASP.NET Core Web API that we are going to discuss in this
course:
Cross-Platform Support: ASP.NET Core Web APIs can run on Windows, Linux, and
macOS, making your Web APIs platform-independent.
Performance: ASP.NET Core has been designed to have a smaller memory footprint and
improved performance compared to its predecessors. It’s optimized for modern cloud-based
applications.
Routing: Supports attribute routing, which allows the development of -SEO-friendly URLs.
Model Binding and Validation: Automatically maps data from HTTP requests to action
method parameters. Model validation is also automatically performed, and any validation
errors can be handled and returned to the client.
Dependency Injection: Built-in support for dependency injection (DI). This allows for more
modular and testable code.
Middleware Support: ASP.NET Core’s middleware pipeline enables you to add components
that inspect and process HTTP requests/responses, allowing for custom processing like
authentication, logging, encryption and decryption, etc.
Content Negotiation and Serialization: Automatically serializes your data to and from
JSON, XML, or any other format, depending on client preferences and server capabilities.
Versioning: Supports API versioning, which is important for handling new clients with new
APIs without breaking existing clients.
OpenAPI/Swagger Support: Provides built-in support for generating OpenAPI (formerly
Swagger) descriptions of your API, which can then be used to generate beautiful interactive
documentation, client SDK generation, and more.
Security: Supports authentication and authorization mechanisms, including OAuth 2.0, Basic
Authentication, HMAC, JWT (JSON Web Tokens), and more, to secure your web APIs.
Testability: Designed to support unit testing. You can write tests for your API like any other
ASP.NET Core application.
Extensibility: Highly extensible and customizable to suit various needs, from custom filters to
new serialization formats.
Integrated Configuration System: The Web API can read application configuration data
from various sources, like JSON files, environment variables, and more.
Environment-based Configuration: Supports development, staging, and production
environments, allowing different configurations for each environment.
What is Rest?
REST stands for Representational State Transfer. This is an architectural pattern used for
exchanging data over a distributed environment. At 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 access those resources by using HTTP Protocol
methods such as GET, POST, PUT, PATCH, and DELETE.
What are the REST Principles?
The REST architectural pattern specifies a set of constraints that a system should adhere to. Here are
the REST constraints or principles.
Client-Server Constraint:
This constraint specifies that a client sends a request to the server, and the server sends a response
back to the client. This separation of concerns supports the independent development of client- and
server-side logic. That means client applications and server applications should be developed
separately without any dependency on each other. A client should only know resource URIs, and
that’s all.
Stateless Constraint:
The stateless constraint specifies that the client and server communication must be stateless between
requests. That means the server should not be storing anything related to the client on the server. The
request from the client should contain all the necessary information so that the server can identify the
client and process that request. This ensures that each request can be treated independently by the
server.
Cacheable Constraint:
In real-time applications, some data provided by the server is not changed that frequently, like the list
of Countries, the list of States, the list of Cities, and some master data. RESTful APIs can take
advantage of HTTP caching mechanisms. Responses can include cache directives to enable client-
side caching, reducing the load on the server and improving performance.
Uniform Interface Constraint:
The Uniform Interface Constraint defines an interface between the client and the server. Resources
are represented using standard data formats such as JSON or XML. To understand the uniform
interface constraint, first, we need to understand what a resource is and the HTTP verbs such as
GET, PUT, POST, PATCH, and DELETE.
In the context of a RESTFUL Service, resources typically represent data entities. The Product,
Employee, Customer, Country, State, City, etc. are all resources. The HTTP verb (GET, PUT, POST,
PATCH, and DELETE) that is sent with each request tells the API what to do with the resource. Each
resource is identified by a specific URI (Uniform Resource Identifier).
Content Negotiation:
One of the constraints of the REST service is that the client should be able to decide in which format
they want the response – whether they want the response in XML or JSON, etc. This is called Content
Negotiation.
Layered System:
RESTful architectures can be composed of multiple layers, where each layer provides specific
functionality. For example, REST allows us to use a layered system architecture where we deploy the
APIs in server A, store data on server B, and authenticate requests in server C. A client cannot simply
tell whether it is connected directly to the server or to an intermediary along the way. This allows for
scalability, separation of concerns, and ease of maintenance.
By following these principles, RESTful Web APIs provide a standard and scalable approach to
designing and developing web services. They promote loose coupling between clients and servers,
enabling easy integration with various platforms and technologies. RESTful APIs are widely used in
web and mobile application development, enabling clients to interact with server resources in a
flexible and efficient manner.
What are the Differences Between REST and SOAP Services?
Let us discuss the difference between the REST and SOAP service:
SOAP stands for Simple Object Access Protocol, whereas REST stands for Representational
State Transfer.
The SOAP is an XML-based protocol, whereas REST is not a protocol. Rather, it is an
architectural pattern, i.e., resource-based architecture.
SOAP has stateless and state-full implementation specifications, whereas REST is completely
stateless.
SOAP enforces message format as XML, whereas REST does not enforce message format
as XML or JSON.
The SOAP message consists of an envelope with SOAP headers and a body to store the
information we want to send. In contrast, REST uses the HTTP build-in headers (with various
media types) to store the information and uses HTTP Methods such as GET, POST, PUT,
PATCH, and DELETE to perform CRUD operations.
SOAP is operation-based, where services are exposed as operations, while REST is
resource-based, where services are exposed as resources identified by URLs.
REST is more flexible and offers better performance due to its stateless nature and support
for a broader range of data formats. SOAP, with its rigid structure and XML format, is slower.
SOAP performance is slow compared to REST.
REST is generally considered easier to work with and is more commonly used in modern web
service applications, especially for public APIs.
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 is designed specifically for the Windows platform and the .NET
Framework.
ASP.NET Core Web API, on the other hand, is cross-platform and can be run on Windows,
macOS, or Linux, making it more versatile in terms of development and deployment
environments.
Framework and Runtime:
ASP.NET Web API is built on the .NET Framework.
ASP.NET Core Web API uses the .NET Core runtime, which is a more modular and
lightweight framework.
Performance:
ASP.NET Core Web API is known for higher performance than ASP.NET Web API. This is
partly due to ASP.NET Core’s optimized code path, reduced memory footprint, and other
performance improvements.
Development Tools:
ASP.NET Core Web API can be developed using various tools like Visual Studio, Visual
Studio for Mac, or Visual Studio Code and supports C# or F#.
ASP.NET Web API development is predominantly done in Visual Studio using C#, VB, or F#.
API Design:
In ASP.NET Core, MVC combines the features of MVC and Web API, allowing controllers to
return both views (HTML) and data objects (e.g., JSON). This unification simplifies the
development process.
The ASP.NET Web API focused more on creating REST APIs and did not integrate the MVC
features as seamlessly.
Hosting:
ASP.NET Core Web API can be hosted on IIS, Kestrel, Docker, Linux, macOS, and Windows,
offering more flexibility.
ASP.NET Web AP is generally hosted on Internet Information Services (IIS) but can also be
self-hosted.
Dependency Injection:
ASP.NET Core Web API provides built-in comprehensive support for dependency injection.
ASP.NET Web API provides limited support for dependency injection natively. Often requires
third-party libraries like Autofac or Ninject for more complex scenarios.
Middleware:
ASP.NET Core Web provides robust middleware support, allowing for a highly customizable
request/response pipeline.
ASP.NET Web API provides limited middleware support. Uses HTTP handlers and modules
for request processing.
Use Cases:
ASP.NET Core Web API is Ideal for modern web applications that require high performance,
scalability, and cross-platform capabilities.
ASP.NET Web API is Ideal for applications that are firmly within the Windows/.NET
Framework ecosystem.
Choosing Between ASP.NET Web API and ASP.NET Core Web API:
If you’re working on a new project and want the latest features, performance optimizations,
and cross-platform capabilities, ASP.NET Core Web API is recommended.
Suppose you have an existing application based on the .NET Framework or specific
dependencies on Windows-only features. In that case, ASP.NET Web API might be the
appropriate choice, though migration to .NET Core should be considered for long-term
sustainability.