SlideShare une entreprise Scribd logo
1  sur  50
Author: Muhammad Jahanzaib
www.excellium.online
Interview Preparation &
Essential Concepts for
Mastering APIs From Fundamentals to Advanced
Author: Muhammad Jahanzaib
www.excellium.online
An Overview of APIs - Topics
❖ Introduction to APIs
➢ What is an API?
➢ Why are APIs important?
➢ Examples of APIs
❖ Types of APIs
➢ REST APIs
➢ SOAP APIs
➢ GraphQL APIs
❖ How APIs Work
➢ Request-Response Cycle
➢ HTTP Verbs (GET, POST, PUT,
DELETE)
➢ API endpoints
❖ API Authentication
➢ Basic Authentication
➢ API Keys
➢ OAuth
Author: Muhammad Jahanzaib
www.excellium.online
An Overview of APIs - Topics
❖ API Design Best Practices
➢ Versioning
➢ Documentation
➢ Error Handling
➢ Performance
❖ Design Principles for REST API
➢ Resource-oriented Design
➢ HTTP Verb Design
➢ API Endpoint Design
➢ Query Parameter Design
❖ Advanced REST API Concepts
➢ Webhooks
➢ Real-time APIs
➢ Custom HTTP Headers
➢ Caching
➢ Rate Limiting
❖ Overview of API Performance
➢ Why is API Performance important?
➢ Factors affecting API Performance
(Latency, Bandwidth, CPU Utilization)
Author: Muhammad Jahanzaib
www.excellium.online
Instructions for Learning and Interview Preparation
➢ Start with the basics of APIs, including what they are, how they work, and why they're important.
➢ Learn about REST and its key concepts such as resources, URIs, HTTP methods, and status codes.
➢ Understand API design principles such as resource-oriented design, HTTP verb design, and query parameter
design.
➢ Study how to write clear and concise API documentation.
➢ Explore API security best practices for authentication, authorization, and encryption.
➢ Look into API testing and monitoring: Testing and monitoring are essential for ensuring the reliability and
performance of your API. Learn how to test your API using automated tools and how to monitor its usage and
performance.
➢ Stay up to date with industry trends and best practices.
➢ Build your own API and seek feedback to improve your skills and knowledge.
Remember, APIs are vast and complex topics that take time and practice to fully understand. Don't get
discouraged if you encounter difficulties. Instead, keep practicing and seek help when needed.
Good luck!
Author: Muhammad Jahanzaib
www.excellium.online
Introduction to APIs
An API, or Application Programming Interface, is a set of protocols, routines, and tools that enable different
software applications to communicate with each other. It provides a well-defined interface for software
components to interact with each other, allowing for seamless integration and collaboration between
different systems. Essentially, an API is a set of rules that govern how different software components
should communicate with each other.
Key Points:
● Have you ever wondered how different applications and software components interact with each
other? That's where APIs come in!
● APIs, or Application Programming Interfaces, provide a set of rules and protocols that enable
seamless communication between different software applications.
● In this section, we'll explore the fundamentals of APIs and why they are essential for modern
software development.
Definition:
Author: Muhammad Jahanzaib
www.excellium.online
Introduction to APIs
Author: Muhammad Jahanzaib
www.excellium.online
Why are APIs important?
● APIs are the backbone of modern software development, enabling developers to build innovative
applications by combining different software components.
● They allow for faster development, increased efficiency, and better collaboration between different
teams.
● In this section, we'll explore the reasons why APIs are crucial for building robust and scalable
software applications.
Author: Muhammad Jahanzaib
www.excellium.online
Examples of APIs
● APIs are everywhere! From social media
platforms like Twitter to location-based
services like Google Maps, APIs are an
essential component of modern software
applications.
● They enable developers to access pre-built
code and functionality, saving time and
effort in software development.
● In this section, we'll explore some popular
examples of APIs and how they are used in
real-world applications.
Author: Muhammad Jahanzaib
www.excellium.online
How APIs Work - Request-Response Cycle
● When a client application sends a request to
an API, the API processes the request and
sends back a response.
● This request-response cycle is the
fundamental mechanism behind how APIs
work.
● In this section, we'll explore the various
stages of the request-response cycle and
how they contribute to the functioning of
APIs.
Author: Muhammad Jahanzaib
www.excellium.online
Comparison of Front-End vs. Back-End Development in the Context of API
Parameter Front-end Development Back-end Development
Purpose User Interface Server-side Logic
Focus Client-side Server-side
Languages HTML, CSS, JavaScript PHP, Ruby, Python, etc.
Frameworks React, Vue, Angular Express, Flask, Ruby on Rails, etc.
API Interaction Sends API requests Receives API requests
Data Handling JSON, XML, etc. Database Management
Security Client-side security Server-side security
Author: Muhammad Jahanzaib
www.excellium.online
HTTP Request Parameters
● Headers: Headers provide additional information about the request or the client making the request. They consist of a
key-value pair and are separated from the body of the request by a blank line. Common headers include:
○ Content-Type: Indicates the MIME type of the request body. For example, "application/json" for JSON data or
"text/plain" for plain text.
○ Accept: Indicates the MIME types that the client can accept in the response. For example, "application/json" or
"text/html".
○ Authorization: Contains authentication credentials for the request. For example, a JWT token or a basic
authentication username and password.
● Body: The body of an HTTP request contains data that's sent by the client to the server. It's usually only used for POST,
PUT, and PATCH requests, but can be used for other methods as well. The format of the request body depends on the
Content-Type header.
Common types include:
○ application/json: JSON data
○ application/x-www-form-urlencoded: URL-encoded data, e.g. "key1=value1&key2=value2"
○ multipart/form-data: Used for file uploads
● Cookies: Cookies are small pieces of data that are stored on the client-side and sent with each request. They're often
used for authentication, tracking user sessions, and storing user preferences. Cookies are sent in the HTTP request headers
and are automatically included in subsequent requests to the same domain.
For example:
○ Cookie: session_id=1234567890abcdef; user_preferences={"theme":"dark"}
Author: Muhammad Jahanzaib
www.excellium.online
HTTP Request Parameters
● Path Parameters: Path parameters are used to
specify a specific resource or endpoint in the URL path.
They're denoted by a colon (:) followed by the
parameter name.
For example:
○ https://api.example.com/products/:id
● Query Parameters: Query parameters are key-value
pairs that are appended to the end of a URL. They're
used to filter or sort resources, or to provide
additional information about the request. They're
separated from the rest of the URL by a question
mark (?) and from each other by an ampersand (&).
For example:
○ https://api.example.com/products?category
=electronics&price_min=100
Author: Muhammad Jahanzaib
www.excellium.online
Query Parameter Design
Query Parameters are a set of key-value pairs that are appended to the URL of a REST API endpoint. These
parameters can be used to filter, sort, and paginate data. They are an essential part of building flexible and
scalable REST APIs.
Definition:
Key Points:
● Query parameters are optional parameters that allow users to filter or modify the data returned by an API.
● They are added to the URL of an API endpoint after a ? character and separated by & characters.
● Query parameters should be used for filtering and pagination, while resource identifiers should be used for resource
identification.
● Keep query parameters short, meaningful, and consistent.
● Limit the number of query parameters to a reasonable number (ideally less than 10).
● Use default values for query parameters to simplify the API usage.
● Document the query parameters in the API documentation and provide clear examples of how to use them.
Author: Muhammad Jahanzaib
www.excellium.online
Query Parameter Design
Examples:
● To filter data by a specific attribute, use a query parameter such as ?status=active to only retrieve records with an
active status.
● To sort data by a specific attribute, use a query parameter such as ?sort=name to sort the data by name.
● To paginate data, use a combination of limit and offset query parameters such as ?limit=10&offset=20 to retrieve the
next 10 records starting from the 20th record.
Author: Muhammad Jahanzaib
www.excellium.online
Resource-oriented Design
Resource-oriented design is a design approach for building RESTful APIs that emphasizes the use of resources as
the core building blocks of the API. Each resource is represented by a unique URI, and clients can perform CRUD
(Create, Read, Update, and Delete) operations on the resources using the HTTP methods.
Definition:
Key Points:
● Resources are the central building blocks of a RESTful API and represent entities that clients can interact with.
● Each resource is identified by a unique URI and can be accessed using HTTP methods such as GET, POST, PUT, and
DELETE.
● Resources can be nested, allowing for the creation of complex data structures that can be navigated by clients.
● Resource-oriented design promotes a consistent and uniform API design that is easy to understand and use.
● The use of HATEOAS (Hypermedia as the Engine of Application State) is encouraged to provide clients with links to
related resources and actions they can perform on those resources.
Author: Muhammad Jahanzaib
www.excellium.online
HTTP Verb Design
HTTP Verb Design refers to the practice of using the appropriate HTTP methods (verbs) to perform actions on
resources in a REST API. HTTP methods provide a standardized way of indicating the type of action being taken on
a resource, and help to make APIs more predictable and self-explanatory.
Definition:
Key Points:
● Use GET to retrieve a resource or collection of resources. This is a safe and idempotent operation, meaning it can be
repeated without causing any side effects.
● Use POST to create a new resource or perform a non-idempotent operation that modifies an existing resource. POST
requests typically include a request body containing the data for the new or updated resource.
● Use PUT to update an existing resource. PUT requests replace the entire resource with the new data provided in the
request body.
● Use PATCH to perform a partial update of an existing resource. PATCH requests update only the fields that are
included in the request body, leaving all other fields unchanged.
● Use DELETE to delete a resource.
Author: Muhammad Jahanzaib
www.excellium.online
● GET /users - Retrieve a collection of users.
● GET /users/{id} - Retrieve a specific user.
● POST /users - Create a new user.
● PUT /users/{id} - Update an existing user.
● PATCH /users/{id} - Partially update an existing user.
● DELETE /users/{id} - Delete a specific user.
HTTP Verb Design
Examples:
● Use plural nouns to name resources.
● Use HTTP methods to represent the actions that can be performed on resources.
● Use HTTP status codes to provide meaningful responses to clients.
● Use hypermedia to provide links to related resources and actions that can be performed on them.
● Model resources based on the domain-specific requirements of the API.
● Support content negotiation to allow clients to request data in a format that they can consume.
● Document the API resources and their relationships in the API documentation.
Best Practices:
Author: Muhammad Jahanzaib
www.excellium.online
API endpoints
● An API endpoint is a specific URL that is used to access a particular resource on an API server.
● Endpoints typically consist of a base URL and a resource-specific path, allowing for targeted access to API
resources.
● In this section, we'll explore how API endpoints work, how to identify them, and how to use them in API
communication. For example:
https://api.example.com/products/1234
In this example, the endpoint is /products/1234. The API is hosted at https://api.example.com, and the endpoint is used to
identify a specific product with an ID of 1234. The API might return information about the product, or allow the client to update
or delete the product.
Author: Muhammad Jahanzaib
www.excellium.online
Types of APIs
REST (Representational State Transfer) APIs are a type of web service that follow a set of architectural principles
and constraints. They use HTTP requests to retrieve and manipulate data, and typically return responses in JSON
or XML format.
Definition:
Key Points:
● REST APIs are stateless, meaning that each request contains all the information needed to process it.
● They use standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete)
operations on resources.
● REST APIs are widely used and have become the de facto standard for web APIs.
Example:
● A popular example of a REST API is the Twitter API, which allows developers to retrieve tweets, post new tweets, and
perform other operations related to Twitter data.
Author: Muhammad Jahanzaib
www.excellium.online
HTTP Verbs (GET, POST, PUT, DELETE)
● HTTP verbs, also known as HTTP methods,
are an essential part of API communication.
● They define the type of request being made
and the action that needs to be performed on
the requested resource.
● In this section, we'll explore the different
HTTP verbs, their functionalities, and how
they are used in API communication.
Author: Muhammad Jahanzaib
www.excellium.online
HTTP Verbs (GET, POST, PUT, DELETE)
HTTP Verb Parameters Included CRUD Operation Usage
GET Query parameters Read Retrieving resources or data
POST Request body, headers Create
Creating a new resource or
data
PUT Request body, headers Update
Updating an existing resource
or data
PATCH Request body, headers Update
Partially updating an existing
resource or data
DELETE Query parameters, headers Delete
Deleting an existing resource
or data
Author: Muhammad Jahanzaib
www.excellium.online
Status Code Category Description Example
1xx Informational
The request has been received and the
server is continuing to process it
100 Continue: The client should continue
sending the request
2xx Success
The request has been successfully received,
understood, and accepted
200 OK: The request was successful
3xx Redirection
The client must take additional action to
complete the request
301 Moved Permanently: The requested
resource has been moved permanently to a
new URL
4xx Client Error
The request contains bad syntax or cannot
be fulfilled by the server
404 Not Found: The requested resource
could not be found
5xx Server Error
The server failed to fulfill an apparently valid
request
500 Internal Server Error: An unexpected
condition was encountered by the server
HTTP Status Codes and their Descriptions
Author: Muhammad Jahanzaib
www.excellium.online
Types of APIs
SOAP (Simple Object Access Protocol) APIs are a type of web service that use XML for data exchange. They
typically rely on a WSDL (Web Services Description Language) file to describe the service and its operations.
Definition:
Key Points:
● SOAP APIs are more rigid and have stricter rules compared to REST APIs.
● They use a contract-first approach, meaning that the WSDL file defines the operations, data types, and message
formats used by the API.
● SOAP APIs are often used in enterprise environments where reliability and security are critical.
Example:
● An example of a SOAP API is the Amazon Web Services (AWS) API, which provides various services such as cloud
storage, compute resources, and machine learning.
Author: Muhammad Jahanzaib
www.excellium.online
Types of APIs
GraphQL is a query language and runtime for APIs that was developed by Facebook. It allows clients to request
exactly the data they need, and nothing more. GraphQL APIs use a single endpoint to retrieve data, and return
responses in JSON format.
Definition:
Key Points:
● GraphQL APIs allow clients to specify the exact data they need, reducing the amount of data transferred over the
network.
● They use a schema to define the types, fields, and operations available in the API.
● GraphQL APIs are gaining popularity due to their flexibility and efficiency.
Example:
● An example of a GraphQL API is the GitHub API, which allows developers to retrieve information about repositories,
pull requests, and other data related to GitHub.
Author: Muhammad Jahanzaib
www.excellium.online
API Authentication
Authentication is a mechanism that ensures only authorized users or
applications can access the API resources. It helps protect against
unauthorized access and ensures the security and integrity of data. There
are various methods for API authentication, and some of the commonly
used ones are:
Definition:
Types:
1. Basic Authentication
2. API Keys
3. OAuth
Author: Muhammad Jahanzaib
www.excellium.online
API Authentication - Basic Authentication
It's a simple authentication method where the user provides their username and password with each request. The
server verifies the credentials and responds with the requested data if the credentials are valid.
Definition:
Key Points:
● It's easy to implement.
● It's not secure as the credentials are sent in plain text, making it vulnerable to interception.
● It's suitable for low-risk applications or internal APIs.
● The client sends the Authorization header with the "Basic" keyword followed by the base64-encoded username and
password.
Example:
Author: Muhammad Jahanzaib
www.excellium.online
API Authentication - API Keys
It's a more secure method than Basic Authentication, where the client sends an API key with each request. The
server verifies the API key and responds with the requested data if the key is valid.
Definition:
Key Points:
● It's easy to implement and provides a higher level of security than Basic Authentication.
● The API key can be revoked or regenerated to prevent unauthorized access.
● The client sends the API key in the request header or query parameter.
Example:
Author: Muhammad Jahanzaib
www.excellium.online
API Authentication - OAuth
It's an industry-standard protocol for authorization that enables third-party applications to access resources on
behalf of a user without exposing the user's credentials.
Definition:
Key Points:
● It's secure and allows users to control which resources a third-party application can access.
● It involves a series of redirects between the client, the authorization server, and the resource server.
● The client requests an access token from the authorization server, and the access token is used to access the
protected resources.
● There are different types of OAuth grants, such as Authorization Code Grant, Implicit Grant, Client Credentials Grant,
and Resource Owner Password Credentials Grant.
Example:
Author: Muhammad Jahanzaib
www.excellium.online
API Tokens & Their Types
A token is a piece of data that's used to authenticate a user or a client making a request. Tokens are often used in
place of passwords, as they can be more secure and flexible.
Definition:
Types:
1. Access Tokens: Access tokens are used to authenticate a client to an API. They're typically issued after a
client has been authenticated using a username and password, or some other form of authentication.
Access tokens are often time-limited and must be refreshed periodically.
2. Refresh Tokens: Refresh tokens are used to request new access tokens after an old one has expired.
They're often longer-lived than access tokens and can be used to authenticate a client without requiring
the user to re-enter their credentials.
3. JWT Tokens: JWT (JSON Web Tokens) are a type of access token that are encoded as a JSON object.
They contain information about the user and their permissions, as well as an expiration date. JWT tokens
are often used in REST APIs.
4. Session Tokens: Session tokens are used to authenticate a user for the duration of a session. They're
often stored in a cookie and sent with each request.
Author: Muhammad Jahanzaib
www.excellium.online
API Design Best Practices - Versioning
Versioning is the process of managing different versions of an API to ensure backward compatibility and smooth
transition for users.
Definition:
Key Points:
● Versioning helps developers to introduce changes to the API without breaking existing client applications.
● It allows clients to choose which version of the API to use.
● Version numbers should be included in the URI or header of the request to indicate the desired version.
Examples:
➔ https://api.example.com/v1/products/
➔ https://api.example.com/v2/products/
Author: Muhammad Jahanzaib
www.excellium.online
API Design Best Practices - Documentation
API documentation provides developers with information about the API, including its resources,
parameters, and responses.
Definition:
Key Points:
● Clear and concise documentation helps developers understand how to use the API.
● Documentation should include examples of requests and responses, as well as code snippets and
SDKs.
● Good documentation can also improve the adoption rate of the API.
Examples:
● Documentation for Stripe API: https://stripe.com/docs/api
Author: Muhammad Jahanzaib
www.excellium.online
API Design Best Practices - Error Handling
Error handling refers to how an API responds when a client sends an invalid request or when something
goes wrong on the server-side.
Definition:
Key Points:
● Error messages should be clear, concise, and informative.
● Errors should be returned in a consistent format, such as JSON or XML.
● HTTP status codes should be used to indicate the nature of the error.
Examples:
Author: Muhammad Jahanzaib
www.excellium.online
API Design Best Practices - Performance
API performance refers to how quickly an API can process requests and return responses to clients.
Definition:
Key Points:
● APIs should be designed to minimize response times and maximize scalability.
● Caching and compression can be used to improve performance.
● Load testing can be used to identify bottlenecks and optimize performance.
Examples:
● Amazon Web Services (AWS) API Gateway provides features such as caching, request throttling,
and performance monitoring to help optimize API performance.
Author: Muhammad Jahanzaib
www.excellium.online
Advanced API Concepts
APIs are an essential part of modern software development, and
there are various advanced concepts that developers need to be
aware of to create efficient and effective APIs
Some of the advanced API concepts are:
● Rate Limiting
● Webhooks
● Caching
● Real-time APIs
● Custom HTTP Headers
Author: Muhammad Jahanzaib
www.excellium.online
Rate Limiting
Rate limiting is the process of controlling the number of requests that a client can send to an API within a specific time
interval. It's a common technique used to prevent abuse of APIs, protect servers from overloading, and maintain consistent
API performance. The API server typically imposes a limit on the number of requests a client can make over a certain period,
and if the limit is exceeded, the server returns an error response.
Definition:
Key Points:
● Rate limiting is used to control the number of requests that a client can make to an API in a given time period.
● It helps prevent abuse of APIs, protects servers from overloading, and maintains consistent API performance.
● The API server imposes a limit on the number of requests a client can make, and if the limit is exceeded, the server
returns an error response.
Author: Muhammad Jahanzaib
www.excellium.online
Rate Limiting
Example:
● Twitter's API allows developers to make a limited number of requests per 15-minute window to prevent abuse and
maintain API performance.
Author: Muhammad Jahanzaib
www.excellium.online
Webhooks
Webhooks are a way for APIs to send real-time notifications to other applications or services. They enable applications to
receive data and respond to events as they happen, rather than polling for updates at regular intervals. A webhook sends a
request to a specified endpoint when a specific event occurs, such as a new user sign-up or a payment confirmation.
Definition:
Key Points:
● Webhooks are used to send real-time notifications to other applications or services.
● They enable applications to receive data and respond to events as they happen, rather than polling for updates at
regular intervals.
● A webhook sends a request to a specified endpoint when a specific event occurs.
Example:
● Stripe's API uses webhooks to notify merchants of important events, such as a new payment or a refund.
Author: Muhammad Jahanzaib
www.excellium.online
Webhooks
Example:
● Stripe's API uses webhooks to notify merchants of important events, such as a new payment or a refund.
Author: Muhammad Jahanzaib
www.excellium.online
Caching
Caching is the process of storing frequently requested data in memory or on disk to reduce the response time of API
requests. It involves storing the API response in a cache and retrieving it from the cache when the same request is made
again. Caching can significantly improve API performance, reduce server load, and improve scalability.
Definition:
Key Points:
● Caching is used to store frequently requested data to reduce the response time of API requests.
● It involves storing the API response in a cache and retrieving it from the cache when the same request is made again.
● Caching can significantly improve API performance, reduce server load, and improve scalability.
● What Is a Cache Miss? A cache miss is an event in which a system or application makes a request to retrieve data
from a cache, but that specific data is not currently in cache memory.
Author: Muhammad Jahanzaib
www.excellium.online
Caching
Example:
● Facebook's API caches frequently requested data, such as user profiles and posts, to reduce response time and
server load.
Author: Muhammad Jahanzaib
www.excellium.online
Real-time APIs
Real-time APIs are designed to provide immediate updates to clients as soon as data changes on the server. They are
commonly used in applications such as chat applications, gaming, and financial trading platforms. Real-time APIs use
technologies such as websockets and long-polling to establish and maintain a persistent connection between the client and
server.
Definition:
Key Points:
● Real-time APIs provide immediate updates to clients as soon as data changes on the server.
● They are commonly used in applications such as chat applications, gaming, and financial trading platforms.
● Real-time APIs use technologies such as websockets and long-polling to establish and maintain a persistent
connection between the client and server.
Author: Muhammad Jahanzaib
www.excellium.online
Real-time APIs
Example:
● Slack's API uses real-time messaging to provide immediate updates to clients as soon as a new message is
received.
Author: Muhammad Jahanzaib
www.excellium.online
Custom HTTP Headers
Custom HTTP headers provide a way to send additional metadata along with an HTTP request or response. This metadata
can be used for various purposes, such as authentication, caching, and tracking.
Definition:
Key Points:
● Use unique header names that are specific to your API. Avoid using generic names that may conflict with other APIs
or HTTP standards.
● Use the correct syntax for custom headers: start the header name with "X-", followed by a descriptive name in all
caps, separated by hyphens (e.g. "X-API-TOKEN").
● Use custom headers to provide additional information about the request or response. This may include authentication
tokens, caching directives, or tracking information.
● Be mindful of security considerations when using custom headers. Avoid sending sensitive information in headers
that can be intercepted or modified by third parties.
● Use standardized headers whenever possible, instead of custom headers, to ensure interoperability with other APIs
and clients.
Author: Muhammad Jahanzaib
www.excellium.online
● X-API-TOKEN: Used to provide an API
authentication token.
● X-CACHE-TTL: Used to set the time-to-
live for cached responses.
● X-FORWARDED-FOR: Used to identify the
originating IP address of a client
making a request through a proxy.
● X-REQUEST-ID: Used to track a specific
request through the system.
● X-RESPONSE-TIME: Used to provide the
time it took to process a request and
generate a response.
Custom HTTP Headers
Examples:
Author: Muhammad Jahanzaib
www.excellium.online
Overview of API Performance
API performance refers to the speed and responsiveness of an API when
processing requests and returning responses. It plays a crucial role in providing
a positive user experience, optimizing system resources, and enabling efficient
communication between clients and servers.
Why is API Performance important?
1. User Experience: Fast API responses contribute to a seamless user experience, reducing
wait times and enhancing overall satisfaction.
2. Productivity: Efficient APIs enable developers to retrieve data quickly, improving their
productivity and allowing them to build responsive applications.
3. Scalability: High-performance APIs can handle increased traffic and user loads without
sacrificing response times or causing service interruptions.
Author: Muhammad Jahanzaib
www.excellium.online
Factors affecting API Performance
Latency
Latency is the delay between sending a request and receiving a
response. It can be affected by network latency, server processing
time, and database queries. Minimizing latency is crucial for fast
API performance.
Example: A social media API that takes several seconds to
retrieve user posts due to slow database queries experiences high
latency, leading to poor performance.
Bandwidth
Bandwidth refers to the data transfer capacity of the network.
Insufficient bandwidth can result in slow API responses, especially
when transmitting large amounts of data.
Example: An image upload API that restricts bandwidth to a very
low value may cause slow uploads and hinder user experience.
CPU Utilization
API performance can be impacted by high CPU utilization on the
server-side. Complex computations, heavy processing, or inefficient
code can strain server resources and result in slower response
times.
Example: An API that performs resource-intensive computations
on each request may experience high CPU utilization, leading to
slower response times.
External Dependencies
APIs relying on external services or integrations may experience
performance issues if those dependencies encounter delays or
outages. It's important to monitor and optimize interactions with
external services to maintain performance.
Example: An API that relies on a third-party payment gateway
may experience slow response times if the gateway experiences
downtime or network issues.
Author: Muhammad Jahanzaib
www.excellium.online
Example of APIs - Node.js with Express.js
● This example uses Express.js, a popular Node.js
framework for building APIs.
● It defines two API endpoints: one for retrieving users
(GET request) and another for creating a new user
(POST request).
● The logic for retrieving users and creating a new user is
not shown in the code snippet.
● The server listens on port 3000 for incoming requests.
Author: Muhammad Jahanzaib
www.excellium.online
Example of APIs - Integration in React.js
● This example uses the axios library to make an HTTP
GET request to the /api/users endpoint.
● The useEffect hook is used to fetch the users when the
component mounts.
● The fetched users are stored in the component's state
using the useState hook.
● The list of users is rendered in the component's JSX,
mapping over the users array.
Author: Muhammad Jahanzaib
www.excellium.online
Example of APIs - Ruby on Rails with ActionController
● This example demonstrates a UsersController in Ruby on
Rails, a popular web framework.
● It defines two actions: index for retrieving users (GET
request) and create for creating a new user (POST
request).
● The logic for retrieving users and creating a new user is
not shown in the code snippet.
● It utilizes strong parameters (user_params method) to
whitelist and sanitize the request parameters.
● The response is rendered as JSON, and appropriate HTTP
status codes are set.
Author: Muhammad Jahanzaib
www.excellium.online
Example of APIs - Integration in Angular
● This Angular component fetches a list of users from the backend API
and displays their names in an unordered list.
● The User interface defines the structure of a user object.
● The UserListComponent class implements the OnInit interface and
defines the component's logic.
● The http property of type HttpClient is injected via dependency
injection to make HTTP requests.
● In the ngOnInit method, the fetchUsers function is called to retrieve
the users when the component initializes.
● The fetchUsers method uses the http.get method to make an HTTP
GET request to the /users endpoint.
● The fetched users are assigned to the users property using the
subscription's success callback.
● If an error occurs during the HTTP request, the error is logged to the
console using the error callback.
● The list of users is rendered in the component's template using the
*ngFor directive.

Contenu connexe

Similaire à API (Application program interface)

Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfAparna Sharma
 
API & Backend Integration
API & Backend IntegrationAPI & Backend Integration
API & Backend IntegrationElewayte
 
Designing Usable APIs featuring Forrester Research, Inc.
Designing Usable APIs featuring Forrester Research, Inc.Designing Usable APIs featuring Forrester Research, Inc.
Designing Usable APIs featuring Forrester Research, Inc.CA API Management
 
Webinar: Embracing REST APIs through APPSeCONNECT
Webinar: Embracing REST APIs through APPSeCONNECTWebinar: Embracing REST APIs through APPSeCONNECT
Webinar: Embracing REST APIs through APPSeCONNECTAPPSeCONNECT
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfAparna Sharma
 
Fundamental essentials for api design
Fundamental essentials for api designFundamental essentials for api design
Fundamental essentials for api designMichael James Cyrus
 
Fundamental essentials for api design
Fundamental essentials for api designFundamental essentials for api design
Fundamental essentials for api designMichael James Cyrus
 
Fundamental Essentials for API Design
Fundamental Essentials for API DesignFundamental Essentials for API Design
Fundamental Essentials for API DesignMichael James Cyrus
 
6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdf6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdfExpert App Devs
 
RESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanRESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanJexia
 
REST-API's for architects and managers
REST-API's for architects and managersREST-API's for architects and managers
REST-API's for architects and managersPatrick Savalle
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introductionDaniel Toader
 
Practical guide to building public APIs
Practical guide to building public APIsPractical guide to building public APIs
Practical guide to building public APIsReda Hmeid MBCS
 
apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...
apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...
apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...apidays
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboardsDenis Ristic
 
What is an API and How does it work
What is an API and How does it workWhat is an API and How does it work
What is an API and How does it workRahul Vijayanagaram
 

Similaire à API (Application program interface) (20)

Third party api integration
Third party api integrationThird party api integration
Third party api integration
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
API & Backend Integration
API & Backend IntegrationAPI & Backend Integration
API & Backend Integration
 
Designing Usable APIs featuring Forrester Research, Inc.
Designing Usable APIs featuring Forrester Research, Inc.Designing Usable APIs featuring Forrester Research, Inc.
Designing Usable APIs featuring Forrester Research, Inc.
 
Webinar: Embracing REST APIs through APPSeCONNECT
Webinar: Embracing REST APIs through APPSeCONNECTWebinar: Embracing REST APIs through APPSeCONNECT
Webinar: Embracing REST APIs through APPSeCONNECT
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1
 
Fundamental essentials for api design
Fundamental essentials for api designFundamental essentials for api design
Fundamental essentials for api design
 
Fundamental essentials for api design
Fundamental essentials for api designFundamental essentials for api design
Fundamental essentials for api design
 
Fundamental Essentials for API Design
Fundamental Essentials for API DesignFundamental Essentials for API Design
Fundamental Essentials for API Design
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdf6 Best Practices that Make a Great API .pdf
6 Best Practices that Make a Great API .pdf
 
What is the Role of Laravel in API Development?
What is the Role of Laravel in API Development?What is the Role of Laravel in API Development?
What is the Role of Laravel in API Development?
 
RESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanRESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel Mardjan
 
REST-API's for architects and managers
REST-API's for architects and managersREST-API's for architects and managers
REST-API's for architects and managers
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introduction
 
Practical guide to building public APIs
Practical guide to building public APIsPractical guide to building public APIs
Practical guide to building public APIs
 
apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...
apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...
apidays LIVE Paris 2021 - Lessons from the API Stewardship Journey in Azure b...
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards
 
What is an API and How does it work
What is an API and How does it workWhat is an API and How does it work
What is an API and How does it work
 

Dernier

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Dernier (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

API (Application program interface)

  • 1. Author: Muhammad Jahanzaib www.excellium.online Interview Preparation & Essential Concepts for Mastering APIs From Fundamentals to Advanced
  • 2. Author: Muhammad Jahanzaib www.excellium.online An Overview of APIs - Topics ❖ Introduction to APIs ➢ What is an API? ➢ Why are APIs important? ➢ Examples of APIs ❖ Types of APIs ➢ REST APIs ➢ SOAP APIs ➢ GraphQL APIs ❖ How APIs Work ➢ Request-Response Cycle ➢ HTTP Verbs (GET, POST, PUT, DELETE) ➢ API endpoints ❖ API Authentication ➢ Basic Authentication ➢ API Keys ➢ OAuth
  • 3. Author: Muhammad Jahanzaib www.excellium.online An Overview of APIs - Topics ❖ API Design Best Practices ➢ Versioning ➢ Documentation ➢ Error Handling ➢ Performance ❖ Design Principles for REST API ➢ Resource-oriented Design ➢ HTTP Verb Design ➢ API Endpoint Design ➢ Query Parameter Design ❖ Advanced REST API Concepts ➢ Webhooks ➢ Real-time APIs ➢ Custom HTTP Headers ➢ Caching ➢ Rate Limiting ❖ Overview of API Performance ➢ Why is API Performance important? ➢ Factors affecting API Performance (Latency, Bandwidth, CPU Utilization)
  • 4. Author: Muhammad Jahanzaib www.excellium.online Instructions for Learning and Interview Preparation ➢ Start with the basics of APIs, including what they are, how they work, and why they're important. ➢ Learn about REST and its key concepts such as resources, URIs, HTTP methods, and status codes. ➢ Understand API design principles such as resource-oriented design, HTTP verb design, and query parameter design. ➢ Study how to write clear and concise API documentation. ➢ Explore API security best practices for authentication, authorization, and encryption. ➢ Look into API testing and monitoring: Testing and monitoring are essential for ensuring the reliability and performance of your API. Learn how to test your API using automated tools and how to monitor its usage and performance. ➢ Stay up to date with industry trends and best practices. ➢ Build your own API and seek feedback to improve your skills and knowledge. Remember, APIs are vast and complex topics that take time and practice to fully understand. Don't get discouraged if you encounter difficulties. Instead, keep practicing and seek help when needed. Good luck!
  • 5. Author: Muhammad Jahanzaib www.excellium.online Introduction to APIs An API, or Application Programming Interface, is a set of protocols, routines, and tools that enable different software applications to communicate with each other. It provides a well-defined interface for software components to interact with each other, allowing for seamless integration and collaboration between different systems. Essentially, an API is a set of rules that govern how different software components should communicate with each other. Key Points: ● Have you ever wondered how different applications and software components interact with each other? That's where APIs come in! ● APIs, or Application Programming Interfaces, provide a set of rules and protocols that enable seamless communication between different software applications. ● In this section, we'll explore the fundamentals of APIs and why they are essential for modern software development. Definition:
  • 7. Author: Muhammad Jahanzaib www.excellium.online Why are APIs important? ● APIs are the backbone of modern software development, enabling developers to build innovative applications by combining different software components. ● They allow for faster development, increased efficiency, and better collaboration between different teams. ● In this section, we'll explore the reasons why APIs are crucial for building robust and scalable software applications.
  • 8. Author: Muhammad Jahanzaib www.excellium.online Examples of APIs ● APIs are everywhere! From social media platforms like Twitter to location-based services like Google Maps, APIs are an essential component of modern software applications. ● They enable developers to access pre-built code and functionality, saving time and effort in software development. ● In this section, we'll explore some popular examples of APIs and how they are used in real-world applications.
  • 9. Author: Muhammad Jahanzaib www.excellium.online How APIs Work - Request-Response Cycle ● When a client application sends a request to an API, the API processes the request and sends back a response. ● This request-response cycle is the fundamental mechanism behind how APIs work. ● In this section, we'll explore the various stages of the request-response cycle and how they contribute to the functioning of APIs.
  • 10. Author: Muhammad Jahanzaib www.excellium.online Comparison of Front-End vs. Back-End Development in the Context of API Parameter Front-end Development Back-end Development Purpose User Interface Server-side Logic Focus Client-side Server-side Languages HTML, CSS, JavaScript PHP, Ruby, Python, etc. Frameworks React, Vue, Angular Express, Flask, Ruby on Rails, etc. API Interaction Sends API requests Receives API requests Data Handling JSON, XML, etc. Database Management Security Client-side security Server-side security
  • 11. Author: Muhammad Jahanzaib www.excellium.online HTTP Request Parameters ● Headers: Headers provide additional information about the request or the client making the request. They consist of a key-value pair and are separated from the body of the request by a blank line. Common headers include: ○ Content-Type: Indicates the MIME type of the request body. For example, "application/json" for JSON data or "text/plain" for plain text. ○ Accept: Indicates the MIME types that the client can accept in the response. For example, "application/json" or "text/html". ○ Authorization: Contains authentication credentials for the request. For example, a JWT token or a basic authentication username and password. ● Body: The body of an HTTP request contains data that's sent by the client to the server. It's usually only used for POST, PUT, and PATCH requests, but can be used for other methods as well. The format of the request body depends on the Content-Type header. Common types include: ○ application/json: JSON data ○ application/x-www-form-urlencoded: URL-encoded data, e.g. "key1=value1&key2=value2" ○ multipart/form-data: Used for file uploads ● Cookies: Cookies are small pieces of data that are stored on the client-side and sent with each request. They're often used for authentication, tracking user sessions, and storing user preferences. Cookies are sent in the HTTP request headers and are automatically included in subsequent requests to the same domain. For example: ○ Cookie: session_id=1234567890abcdef; user_preferences={"theme":"dark"}
  • 12. Author: Muhammad Jahanzaib www.excellium.online HTTP Request Parameters ● Path Parameters: Path parameters are used to specify a specific resource or endpoint in the URL path. They're denoted by a colon (:) followed by the parameter name. For example: ○ https://api.example.com/products/:id ● Query Parameters: Query parameters are key-value pairs that are appended to the end of a URL. They're used to filter or sort resources, or to provide additional information about the request. They're separated from the rest of the URL by a question mark (?) and from each other by an ampersand (&). For example: ○ https://api.example.com/products?category =electronics&price_min=100
  • 13. Author: Muhammad Jahanzaib www.excellium.online Query Parameter Design Query Parameters are a set of key-value pairs that are appended to the URL of a REST API endpoint. These parameters can be used to filter, sort, and paginate data. They are an essential part of building flexible and scalable REST APIs. Definition: Key Points: ● Query parameters are optional parameters that allow users to filter or modify the data returned by an API. ● They are added to the URL of an API endpoint after a ? character and separated by & characters. ● Query parameters should be used for filtering and pagination, while resource identifiers should be used for resource identification. ● Keep query parameters short, meaningful, and consistent. ● Limit the number of query parameters to a reasonable number (ideally less than 10). ● Use default values for query parameters to simplify the API usage. ● Document the query parameters in the API documentation and provide clear examples of how to use them.
  • 14. Author: Muhammad Jahanzaib www.excellium.online Query Parameter Design Examples: ● To filter data by a specific attribute, use a query parameter such as ?status=active to only retrieve records with an active status. ● To sort data by a specific attribute, use a query parameter such as ?sort=name to sort the data by name. ● To paginate data, use a combination of limit and offset query parameters such as ?limit=10&offset=20 to retrieve the next 10 records starting from the 20th record.
  • 15. Author: Muhammad Jahanzaib www.excellium.online Resource-oriented Design Resource-oriented design is a design approach for building RESTful APIs that emphasizes the use of resources as the core building blocks of the API. Each resource is represented by a unique URI, and clients can perform CRUD (Create, Read, Update, and Delete) operations on the resources using the HTTP methods. Definition: Key Points: ● Resources are the central building blocks of a RESTful API and represent entities that clients can interact with. ● Each resource is identified by a unique URI and can be accessed using HTTP methods such as GET, POST, PUT, and DELETE. ● Resources can be nested, allowing for the creation of complex data structures that can be navigated by clients. ● Resource-oriented design promotes a consistent and uniform API design that is easy to understand and use. ● The use of HATEOAS (Hypermedia as the Engine of Application State) is encouraged to provide clients with links to related resources and actions they can perform on those resources.
  • 16. Author: Muhammad Jahanzaib www.excellium.online HTTP Verb Design HTTP Verb Design refers to the practice of using the appropriate HTTP methods (verbs) to perform actions on resources in a REST API. HTTP methods provide a standardized way of indicating the type of action being taken on a resource, and help to make APIs more predictable and self-explanatory. Definition: Key Points: ● Use GET to retrieve a resource or collection of resources. This is a safe and idempotent operation, meaning it can be repeated without causing any side effects. ● Use POST to create a new resource or perform a non-idempotent operation that modifies an existing resource. POST requests typically include a request body containing the data for the new or updated resource. ● Use PUT to update an existing resource. PUT requests replace the entire resource with the new data provided in the request body. ● Use PATCH to perform a partial update of an existing resource. PATCH requests update only the fields that are included in the request body, leaving all other fields unchanged. ● Use DELETE to delete a resource.
  • 17. Author: Muhammad Jahanzaib www.excellium.online ● GET /users - Retrieve a collection of users. ● GET /users/{id} - Retrieve a specific user. ● POST /users - Create a new user. ● PUT /users/{id} - Update an existing user. ● PATCH /users/{id} - Partially update an existing user. ● DELETE /users/{id} - Delete a specific user. HTTP Verb Design Examples: ● Use plural nouns to name resources. ● Use HTTP methods to represent the actions that can be performed on resources. ● Use HTTP status codes to provide meaningful responses to clients. ● Use hypermedia to provide links to related resources and actions that can be performed on them. ● Model resources based on the domain-specific requirements of the API. ● Support content negotiation to allow clients to request data in a format that they can consume. ● Document the API resources and their relationships in the API documentation. Best Practices:
  • 18. Author: Muhammad Jahanzaib www.excellium.online API endpoints ● An API endpoint is a specific URL that is used to access a particular resource on an API server. ● Endpoints typically consist of a base URL and a resource-specific path, allowing for targeted access to API resources. ● In this section, we'll explore how API endpoints work, how to identify them, and how to use them in API communication. For example: https://api.example.com/products/1234 In this example, the endpoint is /products/1234. The API is hosted at https://api.example.com, and the endpoint is used to identify a specific product with an ID of 1234. The API might return information about the product, or allow the client to update or delete the product.
  • 19. Author: Muhammad Jahanzaib www.excellium.online Types of APIs REST (Representational State Transfer) APIs are a type of web service that follow a set of architectural principles and constraints. They use HTTP requests to retrieve and manipulate data, and typically return responses in JSON or XML format. Definition: Key Points: ● REST APIs are stateless, meaning that each request contains all the information needed to process it. ● They use standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources. ● REST APIs are widely used and have become the de facto standard for web APIs. Example: ● A popular example of a REST API is the Twitter API, which allows developers to retrieve tweets, post new tweets, and perform other operations related to Twitter data.
  • 20. Author: Muhammad Jahanzaib www.excellium.online HTTP Verbs (GET, POST, PUT, DELETE) ● HTTP verbs, also known as HTTP methods, are an essential part of API communication. ● They define the type of request being made and the action that needs to be performed on the requested resource. ● In this section, we'll explore the different HTTP verbs, their functionalities, and how they are used in API communication.
  • 21. Author: Muhammad Jahanzaib www.excellium.online HTTP Verbs (GET, POST, PUT, DELETE) HTTP Verb Parameters Included CRUD Operation Usage GET Query parameters Read Retrieving resources or data POST Request body, headers Create Creating a new resource or data PUT Request body, headers Update Updating an existing resource or data PATCH Request body, headers Update Partially updating an existing resource or data DELETE Query parameters, headers Delete Deleting an existing resource or data
  • 22. Author: Muhammad Jahanzaib www.excellium.online Status Code Category Description Example 1xx Informational The request has been received and the server is continuing to process it 100 Continue: The client should continue sending the request 2xx Success The request has been successfully received, understood, and accepted 200 OK: The request was successful 3xx Redirection The client must take additional action to complete the request 301 Moved Permanently: The requested resource has been moved permanently to a new URL 4xx Client Error The request contains bad syntax or cannot be fulfilled by the server 404 Not Found: The requested resource could not be found 5xx Server Error The server failed to fulfill an apparently valid request 500 Internal Server Error: An unexpected condition was encountered by the server HTTP Status Codes and their Descriptions
  • 23. Author: Muhammad Jahanzaib www.excellium.online Types of APIs SOAP (Simple Object Access Protocol) APIs are a type of web service that use XML for data exchange. They typically rely on a WSDL (Web Services Description Language) file to describe the service and its operations. Definition: Key Points: ● SOAP APIs are more rigid and have stricter rules compared to REST APIs. ● They use a contract-first approach, meaning that the WSDL file defines the operations, data types, and message formats used by the API. ● SOAP APIs are often used in enterprise environments where reliability and security are critical. Example: ● An example of a SOAP API is the Amazon Web Services (AWS) API, which provides various services such as cloud storage, compute resources, and machine learning.
  • 24. Author: Muhammad Jahanzaib www.excellium.online Types of APIs GraphQL is a query language and runtime for APIs that was developed by Facebook. It allows clients to request exactly the data they need, and nothing more. GraphQL APIs use a single endpoint to retrieve data, and return responses in JSON format. Definition: Key Points: ● GraphQL APIs allow clients to specify the exact data they need, reducing the amount of data transferred over the network. ● They use a schema to define the types, fields, and operations available in the API. ● GraphQL APIs are gaining popularity due to their flexibility and efficiency. Example: ● An example of a GraphQL API is the GitHub API, which allows developers to retrieve information about repositories, pull requests, and other data related to GitHub.
  • 25. Author: Muhammad Jahanzaib www.excellium.online API Authentication Authentication is a mechanism that ensures only authorized users or applications can access the API resources. It helps protect against unauthorized access and ensures the security and integrity of data. There are various methods for API authentication, and some of the commonly used ones are: Definition: Types: 1. Basic Authentication 2. API Keys 3. OAuth
  • 26. Author: Muhammad Jahanzaib www.excellium.online API Authentication - Basic Authentication It's a simple authentication method where the user provides their username and password with each request. The server verifies the credentials and responds with the requested data if the credentials are valid. Definition: Key Points: ● It's easy to implement. ● It's not secure as the credentials are sent in plain text, making it vulnerable to interception. ● It's suitable for low-risk applications or internal APIs. ● The client sends the Authorization header with the "Basic" keyword followed by the base64-encoded username and password. Example:
  • 27. Author: Muhammad Jahanzaib www.excellium.online API Authentication - API Keys It's a more secure method than Basic Authentication, where the client sends an API key with each request. The server verifies the API key and responds with the requested data if the key is valid. Definition: Key Points: ● It's easy to implement and provides a higher level of security than Basic Authentication. ● The API key can be revoked or regenerated to prevent unauthorized access. ● The client sends the API key in the request header or query parameter. Example:
  • 28. Author: Muhammad Jahanzaib www.excellium.online API Authentication - OAuth It's an industry-standard protocol for authorization that enables third-party applications to access resources on behalf of a user without exposing the user's credentials. Definition: Key Points: ● It's secure and allows users to control which resources a third-party application can access. ● It involves a series of redirects between the client, the authorization server, and the resource server. ● The client requests an access token from the authorization server, and the access token is used to access the protected resources. ● There are different types of OAuth grants, such as Authorization Code Grant, Implicit Grant, Client Credentials Grant, and Resource Owner Password Credentials Grant. Example:
  • 29. Author: Muhammad Jahanzaib www.excellium.online API Tokens & Their Types A token is a piece of data that's used to authenticate a user or a client making a request. Tokens are often used in place of passwords, as they can be more secure and flexible. Definition: Types: 1. Access Tokens: Access tokens are used to authenticate a client to an API. They're typically issued after a client has been authenticated using a username and password, or some other form of authentication. Access tokens are often time-limited and must be refreshed periodically. 2. Refresh Tokens: Refresh tokens are used to request new access tokens after an old one has expired. They're often longer-lived than access tokens and can be used to authenticate a client without requiring the user to re-enter their credentials. 3. JWT Tokens: JWT (JSON Web Tokens) are a type of access token that are encoded as a JSON object. They contain information about the user and their permissions, as well as an expiration date. JWT tokens are often used in REST APIs. 4. Session Tokens: Session tokens are used to authenticate a user for the duration of a session. They're often stored in a cookie and sent with each request.
  • 30. Author: Muhammad Jahanzaib www.excellium.online API Design Best Practices - Versioning Versioning is the process of managing different versions of an API to ensure backward compatibility and smooth transition for users. Definition: Key Points: ● Versioning helps developers to introduce changes to the API without breaking existing client applications. ● It allows clients to choose which version of the API to use. ● Version numbers should be included in the URI or header of the request to indicate the desired version. Examples: ➔ https://api.example.com/v1/products/ ➔ https://api.example.com/v2/products/
  • 31. Author: Muhammad Jahanzaib www.excellium.online API Design Best Practices - Documentation API documentation provides developers with information about the API, including its resources, parameters, and responses. Definition: Key Points: ● Clear and concise documentation helps developers understand how to use the API. ● Documentation should include examples of requests and responses, as well as code snippets and SDKs. ● Good documentation can also improve the adoption rate of the API. Examples: ● Documentation for Stripe API: https://stripe.com/docs/api
  • 32. Author: Muhammad Jahanzaib www.excellium.online API Design Best Practices - Error Handling Error handling refers to how an API responds when a client sends an invalid request or when something goes wrong on the server-side. Definition: Key Points: ● Error messages should be clear, concise, and informative. ● Errors should be returned in a consistent format, such as JSON or XML. ● HTTP status codes should be used to indicate the nature of the error. Examples:
  • 33. Author: Muhammad Jahanzaib www.excellium.online API Design Best Practices - Performance API performance refers to how quickly an API can process requests and return responses to clients. Definition: Key Points: ● APIs should be designed to minimize response times and maximize scalability. ● Caching and compression can be used to improve performance. ● Load testing can be used to identify bottlenecks and optimize performance. Examples: ● Amazon Web Services (AWS) API Gateway provides features such as caching, request throttling, and performance monitoring to help optimize API performance.
  • 34. Author: Muhammad Jahanzaib www.excellium.online Advanced API Concepts APIs are an essential part of modern software development, and there are various advanced concepts that developers need to be aware of to create efficient and effective APIs Some of the advanced API concepts are: ● Rate Limiting ● Webhooks ● Caching ● Real-time APIs ● Custom HTTP Headers
  • 35. Author: Muhammad Jahanzaib www.excellium.online Rate Limiting Rate limiting is the process of controlling the number of requests that a client can send to an API within a specific time interval. It's a common technique used to prevent abuse of APIs, protect servers from overloading, and maintain consistent API performance. The API server typically imposes a limit on the number of requests a client can make over a certain period, and if the limit is exceeded, the server returns an error response. Definition: Key Points: ● Rate limiting is used to control the number of requests that a client can make to an API in a given time period. ● It helps prevent abuse of APIs, protects servers from overloading, and maintains consistent API performance. ● The API server imposes a limit on the number of requests a client can make, and if the limit is exceeded, the server returns an error response.
  • 36. Author: Muhammad Jahanzaib www.excellium.online Rate Limiting Example: ● Twitter's API allows developers to make a limited number of requests per 15-minute window to prevent abuse and maintain API performance.
  • 37. Author: Muhammad Jahanzaib www.excellium.online Webhooks Webhooks are a way for APIs to send real-time notifications to other applications or services. They enable applications to receive data and respond to events as they happen, rather than polling for updates at regular intervals. A webhook sends a request to a specified endpoint when a specific event occurs, such as a new user sign-up or a payment confirmation. Definition: Key Points: ● Webhooks are used to send real-time notifications to other applications or services. ● They enable applications to receive data and respond to events as they happen, rather than polling for updates at regular intervals. ● A webhook sends a request to a specified endpoint when a specific event occurs. Example: ● Stripe's API uses webhooks to notify merchants of important events, such as a new payment or a refund.
  • 38. Author: Muhammad Jahanzaib www.excellium.online Webhooks Example: ● Stripe's API uses webhooks to notify merchants of important events, such as a new payment or a refund.
  • 39. Author: Muhammad Jahanzaib www.excellium.online Caching Caching is the process of storing frequently requested data in memory or on disk to reduce the response time of API requests. It involves storing the API response in a cache and retrieving it from the cache when the same request is made again. Caching can significantly improve API performance, reduce server load, and improve scalability. Definition: Key Points: ● Caching is used to store frequently requested data to reduce the response time of API requests. ● It involves storing the API response in a cache and retrieving it from the cache when the same request is made again. ● Caching can significantly improve API performance, reduce server load, and improve scalability. ● What Is a Cache Miss? A cache miss is an event in which a system or application makes a request to retrieve data from a cache, but that specific data is not currently in cache memory.
  • 40. Author: Muhammad Jahanzaib www.excellium.online Caching Example: ● Facebook's API caches frequently requested data, such as user profiles and posts, to reduce response time and server load.
  • 41. Author: Muhammad Jahanzaib www.excellium.online Real-time APIs Real-time APIs are designed to provide immediate updates to clients as soon as data changes on the server. They are commonly used in applications such as chat applications, gaming, and financial trading platforms. Real-time APIs use technologies such as websockets and long-polling to establish and maintain a persistent connection between the client and server. Definition: Key Points: ● Real-time APIs provide immediate updates to clients as soon as data changes on the server. ● They are commonly used in applications such as chat applications, gaming, and financial trading platforms. ● Real-time APIs use technologies such as websockets and long-polling to establish and maintain a persistent connection between the client and server.
  • 42. Author: Muhammad Jahanzaib www.excellium.online Real-time APIs Example: ● Slack's API uses real-time messaging to provide immediate updates to clients as soon as a new message is received.
  • 43. Author: Muhammad Jahanzaib www.excellium.online Custom HTTP Headers Custom HTTP headers provide a way to send additional metadata along with an HTTP request or response. This metadata can be used for various purposes, such as authentication, caching, and tracking. Definition: Key Points: ● Use unique header names that are specific to your API. Avoid using generic names that may conflict with other APIs or HTTP standards. ● Use the correct syntax for custom headers: start the header name with "X-", followed by a descriptive name in all caps, separated by hyphens (e.g. "X-API-TOKEN"). ● Use custom headers to provide additional information about the request or response. This may include authentication tokens, caching directives, or tracking information. ● Be mindful of security considerations when using custom headers. Avoid sending sensitive information in headers that can be intercepted or modified by third parties. ● Use standardized headers whenever possible, instead of custom headers, to ensure interoperability with other APIs and clients.
  • 44. Author: Muhammad Jahanzaib www.excellium.online ● X-API-TOKEN: Used to provide an API authentication token. ● X-CACHE-TTL: Used to set the time-to- live for cached responses. ● X-FORWARDED-FOR: Used to identify the originating IP address of a client making a request through a proxy. ● X-REQUEST-ID: Used to track a specific request through the system. ● X-RESPONSE-TIME: Used to provide the time it took to process a request and generate a response. Custom HTTP Headers Examples:
  • 45. Author: Muhammad Jahanzaib www.excellium.online Overview of API Performance API performance refers to the speed and responsiveness of an API when processing requests and returning responses. It plays a crucial role in providing a positive user experience, optimizing system resources, and enabling efficient communication between clients and servers. Why is API Performance important? 1. User Experience: Fast API responses contribute to a seamless user experience, reducing wait times and enhancing overall satisfaction. 2. Productivity: Efficient APIs enable developers to retrieve data quickly, improving their productivity and allowing them to build responsive applications. 3. Scalability: High-performance APIs can handle increased traffic and user loads without sacrificing response times or causing service interruptions.
  • 46. Author: Muhammad Jahanzaib www.excellium.online Factors affecting API Performance Latency Latency is the delay between sending a request and receiving a response. It can be affected by network latency, server processing time, and database queries. Minimizing latency is crucial for fast API performance. Example: A social media API that takes several seconds to retrieve user posts due to slow database queries experiences high latency, leading to poor performance. Bandwidth Bandwidth refers to the data transfer capacity of the network. Insufficient bandwidth can result in slow API responses, especially when transmitting large amounts of data. Example: An image upload API that restricts bandwidth to a very low value may cause slow uploads and hinder user experience. CPU Utilization API performance can be impacted by high CPU utilization on the server-side. Complex computations, heavy processing, or inefficient code can strain server resources and result in slower response times. Example: An API that performs resource-intensive computations on each request may experience high CPU utilization, leading to slower response times. External Dependencies APIs relying on external services or integrations may experience performance issues if those dependencies encounter delays or outages. It's important to monitor and optimize interactions with external services to maintain performance. Example: An API that relies on a third-party payment gateway may experience slow response times if the gateway experiences downtime or network issues.
  • 47. Author: Muhammad Jahanzaib www.excellium.online Example of APIs - Node.js with Express.js ● This example uses Express.js, a popular Node.js framework for building APIs. ● It defines two API endpoints: one for retrieving users (GET request) and another for creating a new user (POST request). ● The logic for retrieving users and creating a new user is not shown in the code snippet. ● The server listens on port 3000 for incoming requests.
  • 48. Author: Muhammad Jahanzaib www.excellium.online Example of APIs - Integration in React.js ● This example uses the axios library to make an HTTP GET request to the /api/users endpoint. ● The useEffect hook is used to fetch the users when the component mounts. ● The fetched users are stored in the component's state using the useState hook. ● The list of users is rendered in the component's JSX, mapping over the users array.
  • 49. Author: Muhammad Jahanzaib www.excellium.online Example of APIs - Ruby on Rails with ActionController ● This example demonstrates a UsersController in Ruby on Rails, a popular web framework. ● It defines two actions: index for retrieving users (GET request) and create for creating a new user (POST request). ● The logic for retrieving users and creating a new user is not shown in the code snippet. ● It utilizes strong parameters (user_params method) to whitelist and sanitize the request parameters. ● The response is rendered as JSON, and appropriate HTTP status codes are set.
  • 50. Author: Muhammad Jahanzaib www.excellium.online Example of APIs - Integration in Angular ● This Angular component fetches a list of users from the backend API and displays their names in an unordered list. ● The User interface defines the structure of a user object. ● The UserListComponent class implements the OnInit interface and defines the component's logic. ● The http property of type HttpClient is injected via dependency injection to make HTTP requests. ● In the ngOnInit method, the fetchUsers function is called to retrieve the users when the component initializes. ● The fetchUsers method uses the http.get method to make an HTTP GET request to the /users endpoint. ● The fetched users are assigned to the users property using the subscription's success callback. ● If an error occurs during the HTTP request, the error is logged to the console using the error callback. ● The list of users is rendered in the component's template using the *ngFor directive.