FastAPI is a modern and fast web framework for building APIs with Python. It is built on top of Starlette for the web parts and Pydantic for the data parts. FastAPI is incredibly fast and supports powerful features such as automatic validation, serialization, and asynchronous programming.
In this tutorial, I will guide you through setting up and using FastAPI to build a simple API.
Prerequisites:
- Python 3.6+
- Pip
Step 1: Install FastAPI
To get started, you first need to install FastAPI using pip. Open your terminal and run the following command:
pip install fastapi
Step 2: Install Uvicorn
FastAPI requires an ASGI server to run. Uvicorn is a lightning-fast ASGI server implementation, and it is recommended to use it with FastAPI. Install Uvicorn using the following command:
pip install uvicorn
Step 3: Create a new file for your API
Create a new Python file, for example main.py
, where we will define our API endpoints. Add the following code to get started:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
This code creates a FastAPI app and defines a simple endpoint that returns a JSON response with a "Hello World" message.
Step 4: Run the API
To run the API, use Uvicorn to start the server. In your terminal, run the following command:
uvicorn main:app --reload
This command tells Uvicorn to run the server with the app
instance from our main.py
file. The --reload
flag enables automatic reloading of the server when any changes are detected.
Step 5: Test the API
Open your web browser and navigate to http://localhost:8000/
. You should see the JSON response with the "Hello World" message.
Step 6: Adding more endpoints
FastAPI makes it easy to define additional endpoints and handle different HTTP methods. For example, you can create a POST endpoint to submit data:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/submit_data")
def submit_data(data: dict):
return {"message": "Data received successfully", "data": data}
In this code, we added a new endpoint /submit_data
that accepts POST requests and expects a JSON payload with data. The data is automatically validated and converted to a Python dictionary by FastAPI using Pydantic.
Step 7: Handling query parameters
You can also define endpoints that accept query parameters. For example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
In this code, we defined an endpoint /items/{item_id}
that accepts an integer item_id
as a path parameter and an optional query parameter q
.
Step 8: Asynchronous programming
FastAPI fully supports asynchronous programming with Python’s async
and await
syntax. If you have functions that perform I/O operations, you can make them asynchronous for improved performance. For example:
from fastapi import FastAPI
import asyncio
app = FastAPI()
async def background_task():
await asyncio.sleep(5)
print("Background task completed")
@app.get("/background")
async def run_background_task():
asyncio.create_task(background_task())
return {"message": "Background task started"}
In this code, we created a background task background_task
that sleeps for 5 seconds before printing a message. The endpoint /background
starts the background task asynchronously and returns a response immediately.
Congratulations! You have successfully built a simple API using FastAPI. You can explore more features such as dependency injection, middleware, and error handling to enhance your API further. FastAPI’s official documentation provides comprehensive information on these and other advanced topics.
All the routes in one router file💀
You shouldn't keep your secrets, keys,, tokens, passwords etc in your code. Accessing them using environment variables is a better approach.
Wow, you made web apis, so cool…