>_
EngineeringNotes
← Back to FastAPI & Python
Module 01

Introduction to FastAPI

The modern, high-performance Python framework for building APIs with speed and type safety.

01

The High-Performance Framework

FastAPI is a modern, high-performance Python web framework used to build APIs quickly and efficiently. It is built on standard Python type hints to provide automatic validation and documentation.

Core Definition

A framework for building APIs with automatic validation, async support, and high performance based on type hints.

Key Features

  • ⚑ Fast: Comparable to Node.js & Go
  • 🧠 Type-Safe: Hint-based validation
  • πŸ”„ Async: Native async/await support
  • πŸ“„ Auto-Docs: Swagger & ReDoc
  • πŸ› οΈ Easy: Easy to learn + production-ready
02

Origin & Framework Comparison

Created by SebastiΓ‘n RamΓ­rez and released in 2018, FastAPI stands on the shoulders of giants:

Starlette β†’ Web handling
Pydantic β†’ Data validation

FastAPI vs Other Frameworks

FeatureFastAPIFlaskDjango
SpeedVery FastMediumMedium
Async SupportNativeLimitedLimited
ValidationAutomaticManualManual
DocsAuto-generatedNoNo
03

Getting Started

πŸ“₯ Installation

Terminal
bash
pip install fastapi uvicorn

πŸš€ First Application (main.py)

main.py
python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"message": "Hello World"}

βš™οΈ Running the Server

Terminal
bash
uvicorn main:app --reload
main file name (main.py)
app FastAPI instance in the file
--reload auto-restart on changes
04

Core Concepts

1. App Instance

The main entry point of your API. Everything is registered to this instance.

app = FastAPI()

2. Routes (Endpoints)

Decorators define the HTTP method and path for each function.

@app.get()@app.post()@app.put()@app.delete()

πŸ“‚ Path Parameters

Variables embedded directly in the URL path, used to identify specific resources.

Path Parameter
python
@app.get("/items/{item_id}")
def get_item(item_id: int):
    return {"item_id": item_id}

πŸ” Query Parameters

Optional parameters added after the ? in the URL, used for filtering or sorting.

Query Parameter
python
@app.get("/search")
def search(q: str):
    return {"query": q}
05

Documentation & Project Structure

πŸ“„

Automatic API Documentation

FastAPI provides industry-standard interactive documentation out-of-the-box. This is a massive point in interviews!

Swagger UI Interactive
http://127.0.0.1:8000/docs
ReDoc Clean Webpage
http://127.0.0.1:8000/redoc

Basic Project Structure

project/
│── main.py
│── requirements.txt
06

Async & Performance

Synchronous vs Asynchronous

⏹️ Sync Route
python
python
@app.get("/sync")
def sync_func():
    return {"message": "Sync"}

Blocking: Waits for completion before moving to the next request.

πŸ”„ Async Route
python
python
@app.get("/async")
async def async_func():
    return {"message": "Async"}

Non-blocking: Can handle other requests while waiting (e.g., for I/O).

When should you use async?
Database CallsExternal API RequestsLarge File I/O
πŸš€

Why is FastAPI so fast?

  • βœ“
    Built-in Async I/O: Native support for asynchronous programming allows handling thousands of concurrent requests.
  • βœ“
    Starlette Base: Runs on a lightweight and extremely fast ASGI framework for building async web services.
  • βœ“
    Pydantic Validation: Uses Python type hints for data validation, which is significantly faster than traditional manual checks.
07

Core Architecture

πŸ›‘οΈ ASGI vs WSGI (Interview Critical)

FeatureWSGIASGI
Execution TypeSynchronousAsynchronous
Standard FrameworksFlask, DjangoFastAPI
Performance HeadroomLowerMuch Higher

πŸ’‘ FastAPI uses ASGI, which enables the framework to handle high concurrency and modern web protocols like WebSockets.

✨ Concepts to Impress Interviewers

πŸ› οΈ
Dependency InjectionPowerful built-in system to manage code sharing and testing.
βœ…
Pydantic ValidationIndustry standard for structured data validation using type hints.
πŸ“‹
OpenAPI SchemaAutomatic generation of standardized API specifications.
πŸ”„
Asynchronous SupportNative integration with Python's async/await keywords.
08

Real-World Applications

πŸ—οΈ
Backend APIs

Providing high-performance unified backends for modern web and mobile ecosystems.

🧩
Microservices

Building lightweight, efficient, and independently scalable service components.

πŸ€–
ML Model Serving

Deploying complex machine learning models with minimal latency and high isolation.

πŸ’‘

🧠 Critical Bonus: ML API Serving

FastAPI is currently the industry standard for serving ML models due to its incredible raw speed, asynchronous nature, and trivial handling of GeoJSON/Complex JSON schemas required by models.

09

Interview Preparation

🧠 Theory Questions

What is FastAPI?β–Ό
Answer:High-performance Python framework for building APIs using type hints for automatic validation and documentation.
Why is FastAPI faster than Flask?β–Ό
Answer:Support for asynchronous operations (ASGI) and highly optimized validation via Pydantic.
What is ASGI?β–Ό
Answer:Asynchronous Server Gateway Interface - the modern standard for async Python web servers supporting high concurrency.
What is Pydantic?β–Ό
Answer:A library for data validation and settings management using Python 3.6+ type annotations.
Major differences between FastAPI and Flask?β–Ό
Answer:FastAPI is natively async, uses type hints for validation, and auto-generates docs, whereas Flask is primarily synchronous and requires plugins for these features.
What role does Uvicorn play?β–Ό
Answer:Uvicorn is the high-performance ASGI server implementation that actually listens for HTTP requests and passes them to the FastAPI app instance.

πŸ’» Practical Coding Scenarios

Scenario 1
Create a basic FastAPI app with two unique routes
Basic App
python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"msg": "Home"}

@app.get("/about")
def about():
    return {"msg": "About"}
Scenario 2
Implement a Path Parameter requiring an integer
Path Parameter
python
@app.get("/square/{num}")
def square(num: int):
    return {"square": num * num}
Scenario 3
Implement a Query Parameter with a default value
Query Parameter
python
@app.get("/greet")
def greet(name: str = "Guest"):
    return {"message": f"Hello {name}"}
Scenario 4
Create a non-blocking asynchronous route
Async Route
python
@app.get("/async")
async def async_route():
    return {"msg": "Async working"}