Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 What is FastAPI📚 Creating Your First API📚 Running the Server📚 HTTP Methods📚 API Endpoints📚 Request and Response📚 Documentation📚 Testing Basics
Fastapi/Api Basics/Request Response

Request and Response Handling 🔄

Every API interaction involves a request (from client) and response (from server). Understanding this flow is essential.

Request/Response Cycle

Client                              Server
  |                                   |
  |-------- HTTP Request ----------> |
  |         (data to send)            |
  |                                   |
  |                         (Processing)
  |                                   |
  | <------ HTTP Response ----------- |
  |         (data returned)           |
  |                                   |

Making Requests

A request includes:

  • **Method**: GET, POST, PUT, DELETE, PATCH
  • **URL**: Where to send it
  • **Headers**: Metadata (Content-Type, Authorization)
  • **Body**: Data (for POST/PUT requests)
# Example request structure
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "name": "John",
  "email": "john@example.com"
}

Handling Requests in FastAPI

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    email: str

@app.post("/users")
async def create_user(user: User):
    # FastAPI automatically:
    # 1. Parses JSON from request body
    # 2. Validates it matches User model
    # 3. Passes as 'user' parameter
    return {"id": 1, **user.dict()}

Sending Responses

A response includes:

  • **Status Code**: 200, 201, 404, 500, etc.
  • **Headers**: Content-Type, etc.
  • **Body**: Data being returned
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    # Returns 200 status by default
    # Converts dict to JSON automatically
    return {"id": item_id, "name": "Item"}

Request Headers

from fastapi import Header
from typing import Optional

@app.get("/data")
async def get_data(
    user_agent: Optional[str] = Header(None),
    accept_language: Optional[str] = Header(None)
):
    # Access HTTP headers
    return {
        "user_agent": user_agent,
        "accept_language": accept_language
    }

Response Status Codes

from fastapi import status

@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: dict):
    # Returns 201 Created instead of default 200
    return user

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    if not item:
        return {"error": "Not found"}  # Still 200
    return item

Request/Response Example

from pydantic import BaseModel

class Product(BaseModel):
    name: str
    price: float

@app.post("/products")
async def create_product(product: Product):
    # Request: {
    #   "name": "Laptop",
    #   "price": 999.99
    # }
    #
    # Response: {
    #   "id": 1,
    #   "name": "Laptop",
    #   "price": 999.99,
    #   "created": "2024-03-02"
    # }
    return {
        "id": 1,
        **product.dict(),
        "created": "2024-03-02"
    }

🔑 Key Takeaways

  • ✅ Request contains method, URL, headers, and body
  • ✅ Response contains status code, headers, and body
  • ✅ FastAPI automatically parses JSON requests
  • ✅ FastAPI automatically serializes JSON responses
  • ✅ Use status codes to indicate success/failure
  • ✅ Headers provide additional metadata
  • ✅ Body contains the actual data

Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn