FastAPI Tutorial: Build APIs with Python Instantly

profile-picture
Vinayak ShindeSoftware Engineerauthor linkedin
Published On
Updated On
Table of Content
up_arrow

APIs (Application Programming Interfaces) are essential for building modern applications. FastAPI is a powerful, high-performance web framework for Python that allows you to build APIs quickly and efficiently. In this tutorial, we’ll explore FastAPI, its features, and how to build a simple API from scratch.

What is FastAPI?

FastAPI is a modern, fast (high-performance), and easy-to-use web framework for building APIs with Python 3.6+ based on standard Python type hints. It’s designed to be easy to use while offering features that make API development faster and more robust.

Key Features of FastAPI:

  • High Performance: As fast as Node.js and Go, thanks to Starlette and Pydantic.

  • Automatic Documentation: Generates OpenAPI and Swagger UI documentation automatically.

  • Type Safety: Uses Python type hints for automatic data validation.

  • Asynchronous Support: Fully compatible with async and await for non-blocking requests.

  • Dependency Injection: Supports dependency injection for better code organization.

  • Data Validation: Pydantic ensures data integrity and validation.

Installation

Before starting, ensure you have Python 3.6+ installed. Then, install FastAPI and Uvicorn (an ASGI server) using pip:

pip install fastapi uvicorn


Creating a Basic FastAPI App

Let’s create a simple FastAPI application.

1. Create a Python file

(e.g., main.py) and add the following code:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}

2. Running the Server

Run the application using Uvicorn:

uvicorn main:app --reload

Your API will be available at http://localhost:8000/. You can access the automatic documentation at:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc


Creating API Endpoints

fastapi components


1. Path Parameters

You can define dynamic paths using parameters:

@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}

Accessing http://localhost:8000/items/5 will return:

{"item_id": 5}

2. Query Parameters

Query parameters allow passing optional data with API requests:

@app.get("/users")
def get_users(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}

Example: http://localhost:8000/users?skip=5&limit=15

3. Request Body (POST Method)

Use pydantic.BaseModel for request body validation:

from pydantic import BaseModel

class Item(BaseModel):
name: str
price: float
is_offer: bool = None

@app.post("/items/")
def create_item(item: Item):
return {"item": item}

Test it by sending a POST request with JSON data:

{
"name": "Laptop",
"price": 1000.0,
"is_offer": true
}


Handling Different HTTP Methods

FastAPI supports all HTTP methods like GET, POST, PUT, DELETE, PATCH:

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_id": item_id, "item": item}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
return {"message": f"Item {item_id} deleted"}


Using Dependency Injection

FastAPI provides dependency injection to help modularize your application.

from fastapi import Depends

def common_parameters(q: str = None, limit: int = 10):
return {"q": q, "limit": limit}

@app.get("/search/")
def search(params: dict = Depends(common_parameters)):
return params


Handling Authentication

FastAPI supports OAuth2 authentication with JWT (JSON Web Tokens):

from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}


Middleware and Background Tasks

You can use middleware for global request handling:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

You can also run background tasks:

from fastapi import BackgroundTasks

def write_log(message: str):
with open("log.txt", "a") as f:
f.write(message + "\n")

@app.post("/log")
def log_message(message: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, message)
return {"message": "Log task added"}


Conclusion

FastAPI is an excellent choice for building high-performance APIs with Python. It provides built-in validation, automatic documentation, and modern development features that make API building fast and efficient. With its async support and dependency injection, FastAPI is suitable for a wide range of applications, from small projects to enterprise solutions.

Try out FastAPI today and experience the ease of building APIs instantly!

Schedule a call now
Start your offshore web & mobile app team with a free consultation from our solutions engineer.

We respect your privacy, and be assured that your data will not be shared