Unit - 6
RESTful APIsβ
1. Introduction to RESTful APIsβ
1.1 REST Architecture Overviewβ
1.1.1 Definition of REST (Representational State Transfer)β
REST (Representational State Transfer) is an architectural style used to design networked applications.
- Introduced by Roy Fielding
- Based on standard web protocols (HTTP)
- Uses resources and representations to communicate
π REST is not a protocol, but a set of design principles
1.1.2 REST as Architectural Style for Web Servicesβ
REST defines how web services should be structured:
- Uses stateless communication
- Follows client-server architecture
- Relies on standard HTTP methods
π Helps in building:
- Scalable
- Maintainable
- Efficient APIs
1.1.3 REST API Definitionβ
A REST API is an interface that allows communication between client and server using REST principles.
- Uses HTTP methods (GET, POST, etc.)
- Exchanges data in formats like JSON or XML
- Operates on resources identified by URLs
Example:
/users
/products/10
1.1.4 Comparison with SOAP (Lightweight vs Heavyweight)β
| Feature | REST | SOAP |
|---|---|---|
| Type | Architectural style | Protocol |
| Data Format | JSON, XML | XML only |
| Complexity | Simple | Complex |
| Performance | Fast | Slower |
| Flexibility | High | Low |
π REST is preferred for modern web applications
1.1.5 Advantages of REST (Scalability, Flexibility, Performance)β
1. Scalability
- Stateless design allows easy scaling
- Servers donβt store client state
2. Flexibility
- Supports multiple data formats
- Works with different platforms
3. Performance
- Lightweight communication
- Uses caching and efficient HTTP methods
1.2 Working of REST APIsβ
1.2.1 Client-Server Communicationβ
- Client sends request
- Server processes it
- Server returns response
π Separation of concerns:
- Client β UI
- Server β logic & data
1.2.2 Request-Response Modelβ
- Every interaction follows this cycle
1.2.3 Use of HTTP Protocolβ
REST APIs use HTTP methods:
- GET β retrieve data
- POST β create data
- PUT β update data
- DELETE β remove data
π HTTP is the foundation of REST
1.2.4 Resource-Based Interactionβ
REST treats everything as a resource:
- Users
- Products
- Orders
Each resource is identified by a URL:
/users/1
/products/5
π Operations are performed on resources
1.2.5 Response Formats (JSON, XML, HTML, Images)β
REST APIs can return different formats:
- JSON (most common)
- XML
- HTML
- Images
Example JSON:
{
"id": 1,
"name": "Ankur"
}
1.2.6 JSON as Most Popular Data Formatβ
JSON (JavaScript Object Notation) is widely used because:
- Lightweight and fast
- Easy to read and write
- Language-independent
Example:
{
"username": "ankur",
"email": "ankur@example.com"
}
π Preferred format for modern REST APIs
π― Key Points (Exam Focus)β
- REST = architectural style for web services
- REST API uses HTTP methods and URLs
- Stateless communication
- Resource-based design
- JSON is most commonly used format
- REST is faster and more flexible than SOAP
- Client β Server via request-response model
2. HTTP Protocol in REST APIsβ
2.1 Introduction to HTTPβ
2.1.1 Definition of HTTP Protocolβ
HTTP (HyperText Transfer Protocol) is the foundation of communication on the web.
- Used to transfer data between client and server
- Works on a requestβresponse model
- Operates over TCP/IP
π It defines how messages are formatted and transmitted
2.1.2 Role of HTTP in REST APIsβ
REST APIs are built on top of HTTP:
- HTTP methods β define actions (GET, POST, etc.)
- URLs β identify resources
- Headers β carry metadata
- Body β carries data
π HTTP acts as the communication layer for REST
2.1.3 Stateless Nature of HTTPβ
HTTP is stateless, meaning:
- Each request is independent
- Server does not store client state
Example:
Request 1 β Server processes β forgets
Request 2 β treated as new request
π Benefits:
- Scalability
- Simplicity
π§ HTTP Communication Flowβ
2.2 HTTP Methods (CRUD Operations)β
HTTP methods define actions on resources.
2.2.1 GET Methodβ
2.2.1.1 Retrieve Resourceβ
- Used to fetch data
- Does not modify server state
Example:
/users
2.2.1.2 Response Codes (200, 404, 400)β
- 200 OK β successful response
- 404 Not Found β resource does not exist
- 400 Bad Request β invalid request
2.2.2 POST Methodβ
2.2.2.1 Create Resourceβ
- Sends data to server
- Creates new resource
2.2.2.2 Response Code 201 Createdβ
- Indicates resource created successfully
2.2.2.3 Location Header Usageβ
- Returns URL of newly created resource
Example:
/users/10
2.2.3 PUT Methodβ
2.2.3.1 Update Resourceβ
- Updates entire resource
2.2.3.2 Create if Not Existsβ
- Creates resource if it doesnβt exist
2.2.3.3 Idempotent Natureβ
- Multiple identical requests β same result
2.2.3.4 Response Codes (200, 204, 201)β
- 200 OK β updated successfully
- 204 No Content β updated, no response body
- 201 Created β new resource created
2.2.4 PATCH Methodβ
2.2.4.1 Partial Updateβ
- Updates only specific fields
2.2.4.2 Patch Instructions (JSON Patch/XML Patch)β
Example:
{
"name": "Updated Name"
}
2.2.4.3 Non-idempotent Natureβ
- Repeated requests may produce different results
2.2.5 DELETE Methodβ
2.2.5.1 Delete Resourceβ
- Removes resource from server
2.2.5.2 Response Code 200 OKβ
- Indicates successful deletion
2.2.6 Other Methodsβ
2.2.6.1 OPTIONS Methodβ
- Returns supported HTTP methods
Example:
Allow: GET, POST, PUT
2.2.6.2 HEAD Methodβ
- Same as GET but returns only headers
- No response body
π§ CRUD Mappingβ
2.3 Idempotence Conceptβ
2.3.1 Definition of Idempotent Operationsβ
An operation is idempotent if:
π Repeating it multiple times gives the same result
2.3.2 Example of Idempotent Operationβ
- GET request
- PUT request
Example:
PUT /users/1 β same result even if repeated
2.3.3 Example of Non-Idempotent Operationβ
- POST request
Example:
POST /users β creates new user each time
π― Key Points (Exam Focus)β
-
HTTP = communication protocol for REST
-
Stateless β each request independent
-
Methods:
- GET β read
- POST β create
- PUT β update
- PATCH β partial update
- DELETE β remove
-
Status codes indicate result
-
Idempotent:
- GET, PUT
-
Non-idempotent:
- POST
-
OPTIONS β allowed methods
-
HEAD β headers only
3. REST API Architectural Constraintsβ
3.1 Overview of Constraintsβ
3.1.1 Definition of REST Constraintsβ
REST constraints are a set of rules that define how a RESTful system should be designed.
- Introduced by Roy Fielding
- Ensure consistency and standardization
- Guide the structure of APIs
π If an API follows these constraints β it is considered RESTful
3.1.2 Importance of Following Constraintsβ
Following REST constraints ensures:
- Scalability β system can handle more users
- Performance β efficient communication
- Simplicity β easy to understand and maintain
- Interoperability β works across platforms
π Ignoring constraints β API becomes inconsistent and hard to manage
3.2 Types of Constraintsβ
3.2.1 Uniform Interfaceβ
This is the core constraint of REST.
-
Standard way of interacting with resources
-
Uses:
- HTTP methods (GET, POST, etc.)
- URLs for resource identification
Key ideas:
- Resource identification via URI
- Manipulation using representations (JSON)
- Self-descriptive messages
π Makes APIs predictable and consistent
3.2.2 Stateless Constraintβ
Each request must contain all required information.
- Server does not store client state
- Every request is independent
Example:
Request 1 β login
Request 2 β must include auth token again
π Benefits:
- Scalability
- Reliability
3.2.3 Cacheable Constraintβ
Responses should be cacheable whenever possible.
- Server indicates if response can be cached
- Improves performance
Example headers:
Cache-Control: max-age=3600
π Reduces:
- Server load
- Response time
3.2.4 Client-Server Architectureβ
Separates client and server responsibilities.
- Client β UI (frontend)
- Server β data + logic
π Benefits:
- Independent development
- Better scalability
3.2.5 Layered Systemβ
System can have multiple layers:
- Client β Proxy β Server β Database
π Benefits:
- Security
- Load balancing
- Modularity
3.2.6 Code on Demand (Optional)β
Server can send executable code to client.
-
Example:
- JavaScript sent to browser
π Rarely used but adds flexibility
3.3 REST System Componentsβ
3.3.1 Clientβ
-
Sends requests to server
-
Examples:
- Browser
- Mobile app
- API client (Postman)
3.3.2 Serverβ
- Processes requests
- Handles business logic
- Interacts with database
3.3.3 Interaction via HTTPβ
-
Communication happens using HTTP
-
Includes:
- Methods (GET, POST, etc.)
- Headers
- Body
π― Key Points (Exam Focus)β
-
REST constraints define structure of APIs
-
6 constraints:
- Uniform Interface
- Stateless
- Cacheable
- Client-Server
- Layered System
- Code on Demand (optional)
-
Stateless β no session storage
-
Cacheable β improves performance
-
Client-server β separation of concerns
-
Interaction happens via HTTP
-
Following constraints β RESTful system
4. URLs and Resource Representationβ
4.1 Resource Identification Using URLsβ
4.1.1 Definition of Resourceβ
A resource is any data or object that can be accessed via an API.
Examples:
- Users
- Products
- Orders
π In REST, everything is treated as a resource
4.1.2 URL as Resource Identifierβ
Each resource is identified using a URL (Uniform Resource Locator).
- Acts as an address of the resource
- Unique for each resource
Example:
/users/1
π /users/1 β identifies a specific user
4.1.3 Endpoint Conceptβ
An endpoint is a specific URL where an API can be accessed.
-
Combines:
- URL
- HTTP method
Example:
GET /users
POST /users
π Same URL + different method = different operation
4.1.4 Hierarchical and Meaningful URLsβ
Good REST APIs use:
- Readable URLs
- Hierarchical structure
Examples:
/users
/users/1
/users/1/orders
π Benefits:
- Easy to understand
- Logical structure
- Better maintainability
4.1.5 URL Examplesβ
4.1.5.1 GET /usersβ
- Retrieves list of users
4.1.5.2 GET /users/{id}β
- Retrieves specific user
4.1.5.3 POST /usersβ
- Creates new user
4.1.5.4 PUT /users/{id}β
- Updates user
4.1.5.5 DELETE /users/{id}β
- Deletes user
π§ URLβOperation Mappingβ
4.2 Resource Representation Formatsβ
4.2.1 JSON Formatβ
JSON (JavaScript Object Notation) is the most widely used format.
- Lightweight
- Easy to read and write
- Language-independent
4.2.2 XML Formatβ
XML (eXtensible Markup Language):
- Structured but more verbose
- Used in older systems (e.g., SOAP)
4.2.3 YAML, CSV, Plain Textβ
Other formats include:
- YAML β human-readable
- CSV β tabular data
- Plain text β simple responses
π JSON is preferred in modern APIs
4.3 Data Transfer Representationβ
4.3.1 Key-Value Structure in JSONβ
JSON uses key-value pairs:
{
"id": 1,
"name": "Ankur"
}
4.3.2 Example JSON Response Structureβ
{
"status": "success",
"data": {
"id": 1,
"username": "ankur"
}
}
π Common structure:
- status
- data
- message (optional)
4.4 HTTP Headers and Content Negotiationβ
4.4.1 Content-Type Headerβ
Defines the format of data being sent.
Example:
Content-Type: application/json
4.4.2 Accept Headerβ
Defines the format client expects in response.
Example:
Accept: application/json
4.4.3 Client-Server Format Agreementβ
Content negotiation ensures:
- Client and server agree on data format
- Correct representation is used
π Improves compatibility
π§ Header Flowβ
4.5 Example API Requestβ
4.5.1 HTTP POST Request Structureβ
POST /users HTTP/1.1
4.5.2 Headers (Host, Content-Type, Accept)β
Host: example.com
Content-Type: application/json
Accept: application/json
4.5.3 JSON Request Bodyβ
{
"username": "ankur",
"email": "ankur@example.com"
}
π§ Full Request Flowβ
π― Key Points (Exam Focus)β
-
Resource = entity (user, product, etc.)
-
URL identifies resource
-
Endpoint = URL + HTTP method
-
Use meaningful and hierarchical URLs
-
JSON is most common format
-
Headers:
- Content-Type β request format
- Accept β response format
-
Content negotiation ensures compatibility
-
REST APIs use structured request/response format
5. Designing and Implementing RESTful APIsβ
5.1 Proper Use of HTTP Methodsβ
5.1.1 GET for Retrievalβ
- Fetch data
- No modification
/users
5.1.2 POST for Creationβ
- Create new resource
- Not idempotent
POST /users
5.1.3 PUT for Update/Createβ
- Update full resource
- Creates if not exists
- Idempotent
PUT /users/1
5.1.4 PATCH for Partial Updateβ
- Update specific fields only
PATCH /users/1
5.1.5 DELETE for Removalβ
- Delete resource
DELETE /users/1
5.2 Designing Resource URIsβ
5.2.1 Meaningful URL Designβ
Rules:
- Use nouns
- Keep hierarchy
- Avoid verbs
5.2.2 Good vs Bad URL Examplesβ
Good:
/users/1/orders
Bad:
/getUserOrders
5.3 API Versioningβ
5.3.1 Need for Versioningβ
- Prevent breaking existing clients
- Support upgrades
5.3.2 URI Versioning (/v1/users)β
/v1/users
5.3.3 Header Versioningβ
Accept: application/vnd.api.v1+json
5.3.4 Query Parameter Versioningβ
/users?version=1
5.4 HTTP Status Codesβ
5.4.1 200 OK β Successβ
5.4.2 201 Created β Resource createdβ
5.4.3 204 No Content β Success, no bodyβ
5.4.4 400 Bad Request β Invalid inputβ
5.4.5 401 Unauthorized β Auth requiredβ
5.4.6 403 Forbidden β Access deniedβ
5.4.7 404 Not Found β Resource missingβ
5.4.8 500 Internal Server Error β Server issueβ
5.5 Error Handlingβ
5.5.1 Structured Error Responseβ
{
"error": "Invalid input",
"code": 400
}
5.5.2 Error Code and Messageβ
- Code β machine-readable
- Message β human-readable
5.5.3 Detailed Error Informationβ
{
"error": "Validation failed",
"fields": {
"email": "Invalid format"
}
}
5.6 HATEOAS Conceptβ
5.6.1 Definitionβ
HATEOAS β API provides links for next actions
5.6.2 Linking Resourcesβ
{
"user": 1,
"links": {
"self": "/users/1",
"orders": "/users/1/orders"
}
}
5.6.3 Navigation via Linksβ
- Client follows links
- No hardcoded URLs
5.7 Authentication and Authorizationβ
5.7.1 Need for Securityβ
- Protect data
- Control access
5.7.2 OAuth 2.0β
- Token-based authorization
- Used in large systems
5.7.3 JWT (JSON Web Tokens)β
- Encoded token
- Contains user data
5.7.4 API Keysβ
- Simple authentication
- Sent with requests
5.7.5 Authorization Header (Bearer Token)β
Authorization: Bearer <token>
5.8 Performance Optimizationβ
5.8.1 Paginationβ
- Limit data size
/users?page=1&limit=10
5.8.2 Caching (ETag, Cache-Control)β
Cache-Control: max-age=3600
ETag: "abc123"
5.8.3 Compression (Gzip)β
- Reduce response size
- Faster transfer
5.9 API Documentationβ
5.9.1 OpenAPI (Swagger)β
- Standard API documentation
- Interactive UI
5.9.2 Endpoint Documentation Structureβ
- URL
- Method
- Parameters
- Request body
- Response
- Status codes
5.10 Logging and Monitoringβ
5.10.1 Logging API Requestsβ
- Track requests
- Debug issues
5.10.2 Monitoring Errors and Usageβ
- Detect failures
- Analyze traffic
π― Key Points (Exam Focus)β
- Use correct HTTP methods
- Design clean, noun-based URLs
- Version APIs properly
- Use proper status codes
- Return structured errors
- HATEOAS = link-based navigation
- Secure APIs (JWT, OAuth, API keys)
- Optimize performance (pagination, caching)
- Document APIs clearly
- Monitor and log API usage
6. Consuming RESTful APIsβ
6.1 Introduction to API Consumptionβ
6.1.1 Definitionβ
API consumption means using an API to send requests and receive data.
- Client interacts with server
- Data exchanged via HTTP
6.1.2 Client Interaction with APIsβ
Flow:
- Client sends request
- Server processes
- Server returns response
6.2 Using cURLβ
6.2.1 Command-Line Tool Overviewβ
- CLI tool to send HTTP requests
- Useful for quick testing
6.2.2 GET Request Using cURLβ
curl http://api.example.com/users
6.2.3 POST Request Using cURLβ
curl -X POST http://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name":"Ankur"}'
6.2.4 Passing Headers (Authorization)β
curl -H "Authorization: Bearer token123" http://api.example.com/users
6.3 Using Postmanβ
6.3.1 GUI-Based Tool Overviewβ
- Graphical API testing tool
- No coding required
6.3.2 Steps to Use Postmanβ
6.3.2.1 Enter API URLβ
Enter endpoint:
http://api.example.com/users
6.3.2.2 Select HTTP Methodβ
- Choose GET / POST / PUT / DELETE
6.3.2.3 Add Headersβ
Example:
Content-Type: application/json
Authorization: Bearer token
6.3.2.4 Add Request Bodyβ
{
"name": "Ankur"
}
6.3.2.5 Send Request and View Responseβ
- Click Send
- View status, headers, body
6.4 Using Python requests Libraryβ
6.4.1 Installation (pip install requests)β
pip install requests
6.4.2 GET Request Exampleβ
import requests
response = requests.get("http://api.example.com/users")
print(response.json())
6.4.3 POST Request Exampleβ
import requests
data = {"name": "Ankur"}
response = requests.post("http://api.example.com/users", json=data)
print(response.json())
6.4.4 Adding Headersβ
headers = {"Authorization": "Bearer token123"}
response = requests.get("http://api.example.com/users", headers=headers)
6.4.5 Handling Errors (try-except)β
import requests
try:
response = requests.get("http://api.example.com/users")
response.raise_for_status()
print(response.json())
except requests.exceptions.RequestException as e:
print("Error:", e)
6.5 Comparison of Toolsβ
6.5.1 cURL (Command Line)β
- Fast
- Lightweight
- No GUI
6.5.2 Postman (GUI)β
- Easy to use
- Visual interface
- Good for testing
6.5.3 Python requests (Automation)β
- Used in scripts/programs
- Best for automation
- Flexible
π― Key Points (Exam Focus)β
-
API consumption = using APIs via HTTP
-
Tools:
- cURL β CLI testing
- Postman β GUI testing
- requests β programmatic usage
-
GET β fetch data
-
POST β send data
-
Headers used for auth & format
-
Error handling important in code
-
Postman best for beginners
-
requests best for automation
7. Building REST APIs with Flaskβ
7.1 Introduction to Flask for APIsβ
7.1.1 Lightweight Frameworkβ
Flask is a micro web framework in Python.
- Minimal setup
- No built-in ORM or auth (you add what you need)
- Full control over structure
7.1.2 Use Casesβ
- REST APIs
- Microservices
- Prototypes
- Small to medium backend systems
7.2 Installationβ
7.2.1 pip install flaskβ
pip install flask
7.3 Basic API Implementationβ
7.3.1 Creating Flask Appβ
from flask import Flask
app = Flask(__name__)
7.3.2 Sample Data Storageβ
users = [
{"id": 1, "name": "Ankur"},
{"id": 2, "name": "John"}
]
7.3.3 GET Endpoint (/users)β
from flask import jsonify
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)
7.3.4 GET Endpoint with ID (/users/{id})β
@app.route('/users/<int:id>', methods=['GET'])
def get_user(id):
user = next((u for u in users if u["id"] == id), None)
if user:
return jsonify(user)
return jsonify({"error": "User not found"}), 404
7.3.5 POST Endpoint (/users)β
from flask import request
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
new_user = {
"id": len(users) + 1,
"name": data["name"]
}
users.append(new_user)
return jsonify(new_user), 201
7.4 Response Handlingβ
7.4.1 jsonify() Functionβ
- Converts Python dict β JSON
- Sets correct headers
7.4.2 Returning JSON Responseβ
return jsonify({"message": "Success"}), 200
7.4.3 Error Response Handling (404)β
return jsonify({"error": "Not Found"}), 404
7.5 Running Flask Appβ
7.5.1 app.run(debug=True)β
if __name__ == "__main__":
app.run(debug=True)
debug=Trueβ auto reload + error details
π§ API Flow (Flask)β
7.6 Advantages of Flaskβ
7.6.1 Simple and Easyβ
- Minimal learning curve
- Quick setup
7.6.2 Large Ecosystemβ
-
Extensions available for:
- Database (SQLAlchemy)
- Auth (Flask-Login)
7.6.3 Suitable for Small/Medium Appsβ
- Lightweight
- Flexible
7.7 Limitations of Flaskβ
7.7.1 No Built-in Async Supportβ
- Not ideal for high concurrency (without extra tools)
7.7.2 Requires Extra Librariesβ
-
No built-in:
- ORM
- Authentication
- Admin panel
π You must integrate manually
π― Key Points (Exam Focus)β
-
Flask = lightweight Python framework
-
Used for building REST APIs
-
Key components:
Flask()β app@app.route()β endpointsjsonify()β JSON response
-
Supports:
- GET
- POST
-
request.get_json()β input data -
Returns status codes (200, 201, 404)
-
Easy but requires extensions for full features
8. Building REST APIs with FastAPIβ
8.1 Introduction to FastAPIβ
8.1.1 Modern High-Performance Frameworkβ
FastAPI is a modern Python framework for building APIs.
- Very fast (uses async)
- Built for performance and scalability
- Based on Python type hints
8.1.2 Built on ASGIβ
-
Uses ASGI (Asynchronous Server Gateway Interface)
-
Supports:
- Async requests
- WebSockets
-
Works with servers like Uvicorn
8.2 Installationβ
8.2.1 pip install fastapi uvicornβ
pip install fastapi uvicorn
8.3 Basic API Implementationβ
8.3.1 Creating FastAPI Appβ
from fastapi import FastAPI
app = FastAPI()
8.3.2 Defining Data Model (Pydantic BaseModel)β
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
8.3.3 GET Endpoint (/users)β
users = []
@app.get("/users")
def get_users():
return users
8.3.4 GET Endpoint with ID (/users/{id})β
from fastapi import HTTPException
@app.get("/users/{id}")
def get_user(id: int):
for user in users:
if user["id"] == id:
return user
raise HTTPException(status_code=404, detail="User not found")
8.3.5 POST Endpointβ
@app.post("/users")
def create_user(user: User):
users.append(user.dict())
return user
8.4 Exception Handlingβ
8.4.1 HTTPException Usageβ
raise HTTPException(status_code=404, detail="Not Found")
8.4.2 Returning Error Responsesβ
- Automatically returns JSON error
Example:
{
"detail": "User not found"
}
8.5 Running FastAPI Serverβ
8.5.1 uvicornβ
uvicorn main:app --reload
mainβ filenameappβ FastAPI instance--reloadβ auto restart
π§ FastAPI Flowβ
8.6 Advantages of FastAPIβ
8.6.1 Built-in Async Supportβ
- Handles concurrent requests efficiently
- High performance
8.6.2 Automatic Validationβ
- Uses Pydantic models
- Validates request data automatically
8.6.3 Auto Documentation (Swagger, ReDoc)β
- Generates interactive API docs
- Available at:
/docs
/redoc
8.7 Limitations of FastAPIβ
8.7.1 Learning Curveβ
-
Requires understanding:
- Async programming
- Type hints
8.7.2 Smaller Ecosystem than Flaskβ
- Fewer extensions compared to Flask
- Still growing
π― Key Points (Exam Focus)β
-
FastAPI = modern, high-performance API framework
-
Built on ASGI (async support)
-
Uses Pydantic for validation
-
Endpoints:
@app.get()@app.post()
-
Uses
HTTPExceptionfor errors -
Run with
uvicorn -
Auto docs available (/docs)
-
Faster than Flask for concurrent requests