To set the stage: what is FastAPI? It’s a framework for building APIs in Python that emphasizes speed, ease-of-use, and automatic generation of interactive documentation. And let me tell you, it’s pretty ***** cool. Here’s an example to illustrate how it works:
# Importing the FastAPI framework
from fastapi import FastAPI
# Creating an instance of the FastAPI class
app = FastAPI()
# Defining a route for the root endpoint
@app.get("/")
# Declaring the function as asynchronous
async def read_root():
# Returning a dictionary with a "Hello" key and "World" value
return {"Hello": "World"}
In this code, we’re creating a new instance of the `FastAPI` class and defining an endpoint at the root URL (i.e., “/”). When you hit that endpoint in your browser or with a tool like cURL, FastAPI automatically converts the JSON response to a Python dictionary for easy consumption by your client code.
FastAPI also supports automatic generation of interactive documentation using Swagger UI and ReDoc. This means you can easily test and document your APIs without having to write any custom code or configuration. Here’s an example:
# Import the FastAPI library
from fastapi import FastAPI
# Create an instance of the FastAPI class
app = FastAPI()
# Define a route for the root endpoint
@app.get("/")
# Use the async keyword to make the function asynchronous
async def read_root():
# Return a dictionary with a "Hello" key and "World" value
return {"Hello": "World"}
# Check if the script is being run directly
if __name__ == "__main__":
# Import the uvicorn library for running the app
import uvicorn
# Run the app on host 0.0.0.0 and port 80
uvicorn.run(app, host="0.0.0.0", port=80)
In this code, we’re running our FastAPI app using the `uvicorn` library (which is included with FastAPI). This allows us to easily test and debug our API locally before deploying it to production. And when you hit that endpoint in your browser or with a tool like cURL, FastAPI automatically converts the JSON response to a Python dictionary for easy consumption by your client code!
But wait, there’s even more! FastAPI also supports automatic conversion between Pydantic models and JSON-formatted payloads. This means you don’t have to write custom serializers like in Django REST Framework or Flask-RESTful. Here’s an example:
# Importing necessary modules
from fastapi import FastAPI, Body # Importing FastAPI and Body from fastapi module
from pydantic import BaseModel # Importing BaseModel from pydantic module
# Creating a Pydantic model for the item
class Item(BaseModel):
name: str # Defining a string attribute for the item's name
price: float # Defining a float attribute for the item's price
# Creating an instance of FastAPI
app = FastAPI()
# Creating a route for creating items
@app.post("/items")
async def create_item(item: Item): # Defining a function that takes in an item of type Item
return item # Returning the item as the response
# The script creates a FastAPI instance and defines a Pydantic model for an item with a name and price attribute. It then creates a route for creating items and uses the Item model as the input type. The function returns the item as the response.
In this code, we’re defining a new Pydantic model called `Item` that has two properties (i.e., name and price). When you hit the “/items” endpoint with an HTTP POST request containing JSON data in the body, FastAPI automatically converts it to a Python object of type `Item`. And when you return that object from your view function, FastAPI automatically serializes it back into JSON format for easy consumption by your client code!
It’s fast, it’s easy-to-use, and it’s perfect for building modern web APIs in Python. Give it a try today and see how much easier your life can be!