← Back to list

Python FastAPI

Python 3.7+ introduces FastAPI, a modern and efficient framework for building high-performance web APIs.

Imran Khan · 2025-09-01 13:41 · 2 claps · 4.7 min read
#fastapi #fastapi-pydantic #fastapi-tutorials #fastapi-python #machine-learning-ai
Open on Medium ↗
Wiki topics: ML · Machine Learning EDU · Education & Learning

Python FastAPI

Python 3.7+ introduces FastAPI, a modern and efficient framework for building high-performance web APIs.

With FastAPI, you can quickly create RESTful APIs while benefiting from automatic data validation and parsing powered by Pydantic.

This makes development faster, safer, and less error-prone, allowing you to focus on your application logic instead of boilerplate code.

It is faster than Java, Node.js and Go.

Key Features:

  • Built-in data validation support using Pydantic.
  • Automatic API Doc generation.
  • High performance using asynchronous programming.

Before deep diving in to FastAPI, we require to have Uvicorn fast ASGI server to run FastAPI. Follow link to read more about Uvicorn in 5 minutes.

GitHub code URL for reference and practice.

RESTful APIs using FastAPI in detail:

FasAPI allow us to define API endpoints and supports GET, POST, PUT, DELETE, and other HTTP methods.

Note: Read comment on top of code while going though code for better understanding.

  1. GET API endpoint using @app.get(“/”) to return JSON in response:
# Default API call 
# Access below API endpoint using localhost:8000
@app.get("/")
def message():
    return {"message" : "Default"}
  1. GET API endpoint to collect name and age from URL:
# Collect name and age from URL
# Access below API endpoint using localhost:8000/getMessage/david/30
@app.get("/getMessage/{name}/{age}", response_model = Person)
def getMessage(name : str, age : int):
    if name :
        return Person(name = name, age = 10)
    else:
        raise HTTPException(status_code=404, details="Something Went Wrong!")
  1. GET API endpoint to collect name and age from query parameter:
# Collect age value from request parameter.
# It is important to define data type as int. 
@app.get("/age")
def getAge(age : int):
    if age:
        return {"age" : age}
  1. POST API endpoint to collect data from request body:
# Get JSON in body and collect values.
@app.post("/message")
async def getMessage(request: Request):
    if request :
        body = await request.json()
        return {"you_response": body.get("message")}
  1. POST API endpoint to collect JSON and mapping to Person class with the help of Pydantic BaseModel:
# Person class Pydanitc BaseModel
class Person(BaseModel):
    name: str  = None
    age: int = 0

# Collect name and age using Person class.
@app.post("/person")
async def getMessage(person: Person):
    print(person)
    return {"return_age": person.age, "return_name" : person.name}   
  1. Below GET API end point to collect headers from request:
# Collect Specific Header from request
@app.get("/headers")
def getMessage(request: Request):

    # Print URI
    print(f"Complete URI: {request.url}")
    headers = dict(request.headers)

    return {"return_header_user_agent" : headers['user-agent']}
  1. Update Person API endpoint using put method and name present in URL
# Put or update person.
@app.put("/person/{name}")
async def udatePerson(name: str):
    print(name)
    return {"update_person": name}
  1. Delete Person API endpoint using delete method and name present in URL
# Delete person.
@app.delete("/person/{name}")
async def deletePerson(name: str):
    print(name)
    return {"delete_person": name}
  1. Create cookie with name user and set Person class as a value:
# Set Person as a cookie
@app.get("/create-user-cookie", response_model=Person)
def set_cookie(response: Response):
    response.set_cookie(key="user", value = Person(name = "David", age = 30), max_age=3600)
    return {"message": "Cookie Set!"}
  1. Read user cookie:
# Read user cookie
@app.get("/read-user-cookie")
def read_cookie(user: str = Cookie(None)):
    if user:
        return {"my_cookie": user}
    else:
        return {"message": "No cookie found"}
  1. Below method to create search API endpoint having search term as q, page and size
# Below method to create search API having search term as q, page and size
# It will throw below error in case data validation fails:
# {"detail":[{"type":"missing","loc":["query","q"],"msg":"Field required","input":null}]}
@app.get("/search")
def search_items(
    # ... represents the parameter is required.
    q: str = Query(..., min_length=3, description="Search term"),

    # default value is 1, ge is greater than or equal to 1
    page: int = Query(1, ge=1, description="Page number"),

    # default value is 1, ge is greater than or equal to 1 and less than equal to 100
    size: int = Query(10, ge=1, le=100, description="Number of items per page")
):
    return {"query": q, "page": page, "size": size}
  1. Below API will throw custom error in case ‘q’ as a search term query parameter didn’t get pass:
# It will throw below custom error in case field validation fails:
# {"detail":"Query parameter 'q' is required!"}
@app.get("/search-term-validation")
def search_items(
    # ... represents the parameter is required.
    q: str = Depends(validate_q)
):
    return {"query": q, "page": page, "size": size}

Start Server:

Use command to start server: uvicorn practice-fastapi:app — reload

OUTPUT:

  1. GET API endpoint using @app.get(“/”):

  1. API endpoint to collect name and age from URL:

  1. API endpoint to collect name and age from query parameter:

  1. POST API call /message to collect data from request body:

  1. POST API endpoint to collect JSON and mapping to Person class with the help of Pydantic BaseModel

  1. Collect built-in headers using Header module:

  1. Update API using put method and name as a query parameter:

  1. Delete API using put method and name as a query parameter:

  1. Create cookie with name user and set Person class as a value

  1. Read user cookie:

  1. Call search API having search term query parameter as q, page and size:

  1. Validate ‘q’ passed as search term query parameter or not:

I hope you found out this article interesting and informative. Please share it with your friends to spread the knowledge.

You can follow me for upcoming blogs follow. Thank you!


메타데이터
post_id
2763825aed86
slug
python-fastapi-2763825aed86
url
https://medium.com/@toimrank/python-fastapi-2763825aed86
canonical_url
https://medium.com/@toimrank/python-fastapi-2763825aed86
author_url
https://medium.com/@toimrank
status
ok
fetched_at
2026-07-17 20:17:52