0% found this document useful (0 votes)
4 views7 pages

Part - 1 Introduction To ASP - NET Core Web API

A doc for asp.net core

Uploaded by

Rishikesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Part - 1 Introduction To ASP - NET Core Web API

A doc for asp.net core

Uploaded by

Rishikesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

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 directly interact 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:
● 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.
● Time Consuming and 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 with the database to manage
the data. So, what will we do? We will add a new Web API Project in between these three Front-end
applications and the backend database. This Web API Project will interact with the database and all
these 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:


● Platform Independence: Web APIs can be consumed by any client that understands
standard HTTP protocols (such as HTTP Methods, HTTP Headers, etc), 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 reusability. Once an API is defined, it can be used by
multiple clients or applications. 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 or users can access sensitive data or perform
certain 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 that allows
different software applications to communicate with each other over the Internet. 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, HTML, 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 data or submitting data.
For example, A weather service API might expose the following endpoints:
● GET https://Example.com/weather/today?location=Mumbai – Retrieves today’s weather
for Mumbai.
● GET https://Example.com/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 Web APIs
(or you can say RESTful Web Services) using ASP.NET Core.

According to Microsoft, the ASP.NET Core Web API is ideal framework for building Restful services
on top of the .NET Platform (.NET Core). These Web API services can then be consumed by a variety
of clients, such as:
● Browsers
● Mobile applications
● Desktop applications
● Console 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., in their daily
lives. 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 we want to expose our data (business data) to browsers and modern devices in a fast, secure,
and easier way, then we should have an API that is 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 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:
1. Resource Identification: Each resource (such as a user, order, 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}.
2. HTTP Methods: Resources are manipulated by sending representations (e.g., JSON, XML)
to the server, typically using standard HTTP methods (GET, POST, PUT, DELETE).
3. 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.
4. 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 https://example.com/books retrieves a list of books.
● GET https://example.com /books/123 retrieves a book with ID 123.
● POST https://example.com/books creates a new book.
● PUT https://example.com/books/123 updates the book with ID 123.
● DELETE https://example.com/books/123 deletes the book with ID 123.

Content Negotiation:
Clients and servers can negotiate the media type used for representing 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 provided with 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 even in 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 it 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 support for dependency
injection, which promotes 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.

You might also like