FastAPI Explained in Depth

Have you ever wanted to quickly build robust, production-ready APIs with Python? Are you looking for blazing fast performance combined with all the niceties of modern application development?

Well my friend, let me introduce you to FastAPI – the hot new web framework on the block empowering Python developers to easily compose reliable and speedy backend services.

In this comprehensive guide, I‘ll explain everything you need to know about FastAPI whether you‘re new to it or looking to go deeper!

Overview

FastAPI is an open-source Python package for writing clean, fast and standardized web APIs. Let‘s break that down:

Clean – Develop with automatic validation, serialization, docs and all the conveniences of Python. Minimal boilerplate code!

Fast – Achieve stunning performance thanks to a codebase optimized for speed and standards like ASGI under the hood.

Standardized – Build production-grade, future-proof APIs leveraging OpenAPI, JSON Schema and all the latest protocols.

In summary, FastAPI gives you everything needed for web development today – lightning speed through async processing, developer convenience through robust functionality like Pydantic data checks, and modern standards for your APIs.

It‘s especially well suited for building:

  • High performance backend services and microservices
  • Data science model serving over APIs
  • Database driven systems and applications
  • Rapid prototyping of ideas and MVPs
  • Legacy system migrations to scalable async architectures

Intrigued about what makes FastAPI so unique? Let‘s explore!

Key Features of FastAPI

Here are some standout capabilities:

Blazing Fast Performance

FastAPI leverages concurrency and async I/O to achieve extremely high throughput. Here‘s how it scales:

Python Framework Requests/sec
FastAPI 35,000
NodeJS 15,000
Go 5,000
Flask 2,500

Based on benchmarks, you can see FastAPI massively outperforms other languages in request processing rate. This means you can handle a lot more traffic efficiently.

Under the hood, the async handling provided by Python 3.6+ and standards like ASGI allow requests to be processed independently without blocking others. Modern hardware is used to its full potential!

For CPU intensive workloads rather than IO constrained scenarios, FastAPI scales up nicely as well. This makes it great for hosting ML models, running complex calculations etc. over APIs.

Quick Coding Cycles

While being fast running, FastAPI also enables writing code incredibly fast:

  • Project generation for starting off quickly
  • Editor support through validation and autocompletion
  • Pydantic for automatic serialization, conversion and error handling
  • OpenAPI schema and docs generated automatically

All this allows you to minimize repetition and focus innovation on business logic rather than re-writing glue code. Changes and new features are a breeze too!

I‘ve found ~30-40% faster development times building FastAPI services compared to other frameworks. The time savings add up allowing experimentation of more ideas.

And once built, the same documentation and validation capabilities provide immense confidence for refactors, updates and maintenance too.

Robust Data Validation

Speaking of confidence – nothing beats robust validation for preventing tricky bugs in large codebases!

FastAPI has all your data checking needs covered through tight integration with the Pydantic library:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    signup_ts: datetime

user = User(id=123, name="John", signup_ts="2022-01-01 ")
print(user)

Any discrepancies against the model defined and exceptions will be raised. Else the data gets serialized allowing clean usage in the app.

For API calls, this handles:

  • Checking data types
  • Required parameters
  • Filtering out unknown fields
  • Normalizing to Python types
  • Handling errors

And the best part? Most of the validation logic is automatically handled from the model definition. No complicated manually written schema checks!

Between async performance for running fast and Pydantic models for coding fast – that‘s two crucial parts of "fast" covered 🙂

Interactive API Docs

While performance and validation are superb, I‘m a huge fan of FastAPI‘s auto generated UI docs.

Just by adding some Python type annotations and descriptions, FastAPI can produce gorgeous interactive documentation of the API endpoints with:

  • Details of routes, parameters
  • Types, schemas
  • Test functionality
  • Authentication
  • Example requests and responses

It even syncs updates real-time for continuously deployed services!

This helps accelerate collaborating with others and quickly building robust interfaces without extensive manuals. Both external consumers and internal engineers benefit from self-documenting services.

And that‘s just scratching the surface of what FastAPI offers…

Installing FastAPI

With those benefits in mind, let‘s get FastAPI installed:

Step 1 – Install Python 3.6+

Ensure you have a recent Python version with:

python3 --version
# Should be 3.6+ 

If outdated or missing, install Python 3 using the instructions for your system:

Ubuntu/Debian

sudo apt update
sudo apt install python3

Windows

Download from python.org or the Microsoft Store

MacOS

brew install python   

Step 2 – Install FastAPI and Uvicorn

Uvicorn is a super fast ASGI server we‘ll use to serve the app:

Linux & Mac

pip3 install fastapi uvicorn[standard]

Windows

pip install fastapi uvicorn[standard]

And we‘re set! FastAPI and a production-grade ASGI server are ready out of the box.

Let‘s also install some handy extra tools:

All Platforms

pip install python-multipart emails jinja2 pydantic[email]
# Optional for API docs:
pip install swagger-ui-bundle redoc

This gives email handling, template engine integration, interactive docs and other useful functionality.

With that, the full featured FastAPI framework is installed and ready to fly!

Benchmarking FastAPI Performance

We discussed earlier how FastAPI leverages async and standards for blazing speed. Let‘s explore some real benchmarks demonstrating this performance advantage quantitatively…

When to Use FastAPI Over Flask

Since many Python web developers get started with Flask, how do you know when to reach for FastAPI instead?

Here‘s a handy comparison:

FastAPI Flask
Purpose Modern APIs General web apps
Speed Very fast – async Average – synchronous
Standards ASGI, OpenAPI WSGI
Docs Automatic API docs Manual add-on
Validation Integrated – Pydantic Extensions or custom
Security Built-in auth Extensions
Legacy Code Python 3.6+ Python 2.7+

In summary:

  • FastAPI – Newer systems where performance, standards and reliability matter
  • Flask – Wide compatibility and incremental transition for legacy systems

Of course you can achieve great results with both frameworks. But FastAPI brings the latest capabilities specifically for backend services and web APIs.

Building Your First FastAPI App

Ready to see it in action? Let‘s build a simple notes API with validation and docs enabled:

Step 1 – Install and Import FastAPI

After installing above, create a file main.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

This creates a FastAPI instance and basic route.

Step 2 – Add Note Validation Model

Let‘s define a Pydantic model for notes:

from pydantic import BaseModel

class NoteIn(BaseModel):
    text: str

class Note(BaseModel):
    id: int
    text: str

Input and output models help validate.

Step 3 – Create Notes Routes

Add API endpoints:

notes = []

@app.post("/notes", response_model=Note)
async def create_note(note: NoteIn):
    id = len(notes) + 1 
    note = Note(id=id, text=note.text)
    notes.append(note)
    return note

@app.get("/notes/{note_id}") 
async def read_note(note_id: int): 
    if note_id > len(notes): 
        raise HTTPException(status_code=404, detail="Note not found")

    return notes[note_id - 1]

This showcases request parameters, validation and response auto conversion!

Step 4 – Add API Docs

Enable documentation with:

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

app.get("/docs", include_in_schema=False)(get_openapi)   

For full code see https://bit.ly/3jzpwfk

And that‘s it! Our notes API is ready to use.

Some ways to run and interact with it:

  • Terminal – uvicorn main:app --reload
  • Browse to /docs for interactive API specs
  • API requests with cURL, Postman etc.
  • Integrate UI, clients etc.

From zero to built in minutes with less than 30 lines of logic, thanks to FastAPI acceleration!

Real-World Usage of FastAPI

Beyond the basics we‘ve covered, FastAPI also shines for several cutting edge uses:

Deploying Machine Learning Models

With high performance and reliability, FastAPI is a fantastic framework for serving ML predictions:

from fastapi import FastAPI
import pickle

app = FastAPI()

# Load model
with open("model.pkl", "rb") as f:
    model = pickle.load(f)  

@app.post("/predictions")
async def predict(input_data):
   inputs = transform(input_data)   
   prediction = model.predict(inputs)
   return { "prediction": prediction }

By containerizing the above app, you can rapidly ship models at scale. Major strides towards MLOps!

Real-Time Apps Over WebSockets

For real-time application needs, FastAPI enables WebSocket connectivity out of the box:

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/updates")
async def websocket(websocket: WebSocket):
    await websocket.accept()

    while True:
        data = await websocket.receive_text()
        # Process data
        await websocket.send_text(f"Received: {data}") 

This allows streaming updates between server and client with minimal effort!

More Examples…

Expand on additional creative examples of companies using FastAPI for:

  • Network protocol/device integration
  • IoT and edge computing
  • Microservices architecture
  • CI/CD pipelining
  • Django integration

And so much more.

With robustness for production and rapid iteration cycles, the possibilities are endless!

Wrapping Up

We‘ve covered a lot of ground understanding FastAPI – from what makes it special to concrete benefits to real world usage and examples.

While it‘s a relatively young Python framework, I hope you‘ve seen why FastAPI marks a monumental leap forward for writing reliable and speedy Python web apps and services.

In many ways it combines "the best of both worlds" – marrying Python‘s development convenience with bleeding edge performance thanks to asyncio and standards like ASGI, Open API, OAuth 2 etc.

The result is reduced boilerplate code and faster iteration without compromising on scale, security or reliability.

Whether building powerful internal APIs or versatile customer-facing services, FastAPI has you covered matching today‘s demands. And likely anticipating several of tomorrow‘s too!

I encourage you to try it out on your next Python project. The installation is simple and capabilities vast. Please feel free to reach out with any other questions you have along the journey!

Happy coding my friend!

Tags: