API
What is [Link] Core Web API?
It helps us create
A framework (toolkit) backend systems that Works well with web
by Microsoft to build can send and receive apps, mobile apps,
Web APIs using C#. data using the and other systems.
internet.
Why Use [Link] Core Web API?
Cross-platform
•You can build APIs that run on Windows, Linux, or Mac.
•It uses .NET Core, which is designed for cross-platform development.
Lightweight and Fast
•It’s optimized to run smoothly even on small servers.
•It’s modular – you only include the features you need.
Built-in Dependency Injection
•Makes it easy to share and reuse code (like services and databases) throughout your app.
•Helps keep your code clean and testable.
Easy Routing System
•You can easily tell the app what URL should do what.
[HttpGet("api/products")]
public IActionResult GetProducts() { ... }
Built-in JSON Support
•Automatically sends and receives data in JSON format (popular format used in web APIs).
Create a Web A mobile app
API in to get
[Link] Core employee
that allows: data
Example
A web
dashboard to Another app
post new to update or
employee delete data
records
API stands for Application Programming Interface. It is a set of rules and
What is an protocols that allows one software application to interact with another.
APIs define the methods and data formats that applications can use to
communicate with each other, making it easier to integrate different
API? systems and share data.
• Key Components:
• Endpoints: URLs where the API can be accessed by clients.
• Methods: Actions that can be performed (e.g., GET, POST, PUT,
DELETE).
• Headers: Additional information sent with the request or response.
• Body: The data sent with the request or response, often in JSON or
XML format.
"REST" stands for REpresentational
State Transfer.
What does A RESTful API follows rules to make web
communication easy and organized.
“RESTful API”
mean? Uses HTTP methods:
• GET → to read data
• POST → to add data
• PUT → to update data
• DELETE → to remove data
How APIs Work
• Let's break down the process of how APIs work into simple steps:
• Request: A client (like a web browser or a mobile app) sends an HTTP request to an API
endpoint.
• Processing: The server hosting the API processes the request, which might involve querying a
database, performing calculations, or invoking other services.
• Response: The server sends back an HTTP response with the requested data or the result of
the operation.
• Example: When you use a weather app on your phone, the app sends a request to a weather
API to fetch the latest weather data. The API processes this request and returns the current
weather information, which is then displayed on your phone.
Client Sends a Request to the Server:
Request and • Client: This can be a web browser, a mobile
Response app, or another server.
• Request: The client initiates a request to the
server. This request is made to a specific URL
(Uniform Resource Locator), which is an
address where the API can be accessed.
• Example:
• URL: [Link]
• Method: GET
Server Processes the Request:
• Server: The server receives the request and processes it. This involves interpreting the request, possibly querying a database or performing some computation, and
preparing a response.
Server Sends Back a Response:
• Response: The server sends a response back to the client. This response typically includes a status code indicating the success or failure of the request, and may also
include data requested by the client.
• Example Response:
• Status Code: 200 OK
• Body: [{ "id": 1, "name": "John Doe" }]
Headers:
Headers are additional information sent with the request. They provide metadata
about the request.
• Common Headers:
• Content-Type: Indicates the media type of the resource (e.g., application/json).
• Authorization: Contains credentials for authenticating the request.
• Accept: Indicates the type of response the client expects.
JSON (JavaScript Object Notation)
•Lightweight format for data exchange
•Easy for humans to read and write
•Easy for machines to parse and generate
•Commonly used for Web APIs
What is
JSON? Example:
{ "name": "Alice", "age": 28, "skills": ["C#", "[Link]",
"SQL"] }
Common Sources:
•Public APIs (JSONPlaceholder, OpenWeatherMap)
•Internal microservices
• The primary purpose of APIs is to enable interoperability
between different software systems. This means that
applications can work together, exchange data, and use
each other's functionalities without needing to
understand the internal workings of each system.
Purpose of • Benefits:
• Modularity: Applications can be broken down into
APIs smaller, manageable components.
• Reusability: Existing functionalities can be reused in
different applications.
• Scalability: Systems can grow by integrating new
functionalities via APIs.
• Flexibility: Different technologies and platforms can
work together seamlessly.
Fetching JSON from APIs in C#
Using HttpClient to get JSON
HttpClient client = new HttpClient();
string json = await [Link]("[Link]
Why do we use HttpClient?
• It's a tool in C# used to call Web APIs (get data from the internet).
• It sends HTTP requests like GET or POST.
• It's better than older tools because:
• It’s faster and more flexible
• Works well with modern APIs
• Think of HttpClient like a browser that asks for data behind the scenes.
Why do we use async and await?
Calling an API takes time (internet is slow sometimes).If we wait for the API
without async, the program freezes.
async and await let the program keep runningwhile waiting for the data.
This makes the app smoother and faster.
Parsing JSON with [Link]
JArray data = [Link](json);
Fetching Why Use JArray?JSON data from APIs is
JSON from often returned as a list/array of objects.
APIs in C# JArray is used to parse this type of data
structure.
Package Required:
•Install via NuGet: [Link]
Asynchronous programming
• Asynchronous programming in C#, the async keyword is used to define a method as asynchronous. When a method is marked as async, it
means that it can contain asynchronous operations, and it can use the await keyword to asynchronously wait for the completion of these
operations.
1. Asynchronous Code Execution
• Asynchronous operations in C# allow certain tasks, like I/O-bound operations (such as network requests or file I/O), to be executed
without blocking the calling thread.
• The await keyword is used to asynchronously wait for the completion of an asynchronous operation. When encountering an await
keyword, the method will pause execution at that point and return control to the caller until the awaited operation is completed.
2. Avoiding Blocking
• Without the async keyword, methods that contain asynchronous operations would typically need to return a Task or Task<T> object to
represent the ongoing asynchronous operation.
• Marking a method as async allows it to return a more expressive type directly, such as Task, Task<T>, or even void. This helps avoid
blocking the calling thread while waiting for the asynchronous operation to complete.
3. Simplified Asynchronous Programming
• Using the async and await keywords makes asynchronous programming in C# more intuitive and readable.
• It allows developers to write code that looks synchronous but behaves asynchronously, making it easier to reason about and maintain.
Asynchronous programming allows code to run without
blocking the main thread
—ideal for I/O-bound tasks (e.g., file, network, DB).
Why use it?
• Improves UI responsiveness
What is
• Avoids thread blocking
Asynchronous • Efficient use of system resources
Programming?
Examples:
• File I/O
• API requests
• Database operations
🧵 Thread:
•The basic unit of execution in a
process.
•Manually managed; heavier on
Understanding resources.
🧵 Task:
Threads and •Represents asynchronous operation.
Tasks •Uses thread pool (lightweight, efficient).
[Link](() => { /* Background Work */
});
async:
• Marks a method as asynchronous.
await:
•Pauses execution until the awaited task completes.
Introducing
public async Task<string> GetDataAsync() async and await
{
HttpClient client = new HttpClient();
string result = await
[Link]("[Link]
;
return result;
}
• async Task<string> GetDataAsync()
• {
• HttpResponseMessage response = await
[Link]("[Link]
a");
• string data = await
[Link]();
• return data;
• }
• Scenario: Building an e-commerce website
• Payment Integration: Use the Stripe API to
handle payments securely. Customers can enter
their payment details, and the API processes the
transaction.
Real-World • Social Media Sharing: Integrate the Facebook
Application API to allow customers to share their purchases
on social media.
• Shipping Information: Use a shipping API to
track packages and update customers with real-
time shipping information.
•
REST API:
• REST, which stands for Representational State Transfer, is an architectural style for designing networked
applications. At its core, a REST API allows systems to interact with each other over the internet using
standard HTTP methods.
Architecture Style:
• REST APIs adhere to a set of architectural principles that govern how resources are defined and addressed.
These principles include:
Uniform Interface:
• Resources are identified by URIs (Uniform Resource Identifiers), and interactions with these resources are
performed using standard HTTP methods such as GET, POST, PUT, and DELETE.
Stateless:
• Each client request to the server contains all the information necessary for the server to fulfill the request.
The server does not store any client state between requests, making it scalable and easier to manage.
Client-Server Architecture:
• REST APIs follow a client-server architecture, where the client initiates requests to the server, and the server
processes these requests and returns responses.
Layered System:
• The architecture is designed to be layered, allowing for intermediaries such as proxies and gateways to
handle requests and responses, providing additional functionalities without affecting the core components.
What Makes an API RESTful?
Uniform Interface:
One of the core principles of RESTful APIs is the establishment of a uniform interface between the client and server. This means that
the communication between the two parties follows a standardized set of rules and conventions. Key components of a uniform
interface include:
• Resource Identification: Resources are uniquely identified by URIs (Uniform Resource Identifiers). Each resource should have a
specific URI that clients can use to access it.
• HTTP Methods: RESTful APIs use standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources. This
uniformity simplifies the interaction between clients and servers.
• Resource Representation: Resources are represented in a standard format, such as JSON or XML, making it easy for clients to
understand and manipulate them.
2. Stateless:
RESTful APIs are designed to be stateless, meaning that each request from a client to the server contains all the information needed
to process that request. The server does not maintain any client state between requests. This statelessness has several implications:
• Scalability: Stateless servers can handle a large number of concurrent requests because they do not need to store client state.
• Simplicity: Statelessness simplifies server implementation and reduces complexity. Servers do not need to manage client sessions
or state transitions.
• Reliability: Statelessness improves reliability by reducing the risk of server-side errors caused by state inconsistencies.
What Makes an API RESTful?
3. Cacheable:
Another important principle of RESTful APIs is cacheability. Responses from a RESTful API can be cached by clients or intermediary systems to improve
efficiency and reduce network traffic. Cacheability offers several benefits:
• Performance: Cached responses can be served quickly, reducing latency and improving the overall performance of the system.
• Reduced Server Load: Caching reduces the number of requests that reach the server, leading to lower server load and improved scalability.
• Network Efficiency: Caching reduces network traffic by serving cached responses locally, closer to the client.
4. Layered System:
RESTful APIs operate within a layered system architecture, where clients cannot distinguish whether they are connected directly to the end server or
through intermediary systems such as proxies or caches. This layered architecture offers several advantages:
• Flexibility: Intermediary systems can provide additional services such as load balancing, caching, or security without impacting the client-server
interaction.
• Scalability: Layered architectures can scale horizontally by adding more intermediary layers to distribute the workload and improve performance.
• Reliability: Intermediary systems can enhance reliability by providing redundancy and failover capabilities, ensuring uninterrupted service even in the
face of failures.
RESTful API
• A RESTful API (Representational State Transfer API) is an architectural style for designing networked applications. It's based on the
principles of REST, which is an acronym for Representational State Transfer. RESTful APIs enable communication between different
software systems over HTTP (Hypertext Transfer Protocol) in a simple, scalable, and standardized way.
• Here's a breakdown of what a RESTful API service entails:
• Resources: In RESTful APIs, everything is considered as a resource, which can be anything that can be named and accessed via a
URI (Uniform Resource Identifier). For example, in a bookstore application, resources could include books, authors, and publishers.
• HTTP Methods: RESTful APIs use standard HTTP methods to perform operations on resources. The most commonly used HTTP
methods in RESTful APIs are:
• GET: Used to retrieve resource representations.
• POST: Used to create new resources.
• PUT: Used to update existing resources.
• DELETE: Used to delete resources.
• PATCH: Used to partially update resources.
• OPTIONS: Used to describe the communication options for the target resource.
• HEAD: Used to retrieve metadata about a resource without transferring the entire representation.
• Uniform Interface: RESTful APIs have a uniform interface, which means that the same set of HTTP methods are used for interacting
with different resources. This simplifies the client-server communication and makes it more predictable.
• Stateless Communication: RESTful APIs are stateless, meaning that each request from a client to the server must contain all the
information necessary to understand the request. This allows for scalability and reliability since the server doesn't need to store
any client state between requests.
• Representation: Resources in a RESTful API are represented in a standardized format, typically JSON (JavaScript Object Notation) or
XML (eXtensible Markup Language). These representations can be easily parsed and understood by different clients and servers.
• Hypermedia as the Engine of Application State (HATEOAS): HATEOAS is a constraint in RESTful APIs that allows the server to
provide links to related resources along with the response. This enables clients to navigate the API dynamically without prior
knowledge of its structure.