FastAPI is a modern web framework for building APIs with Python. It is designed to be fast, simple, and easy to use, making it a great choice for both beginner and experienced developers. In this tutorial, we will walk through building a simple demo API using FastAPI.
Step 1: Install FastAPI
The first step is to install FastAPI. You can do this using pip:
pip install fastapi
Step 2: Install Uvicorn
Next, you will need to install Uvicorn, an ASGI server that FastAPI uses to run your API:
pip install uvicorn
Step 3: Create a new file for your API
Create a new Python file for your API, for example app.py
.
Step 4: Write your first FastAPI app
Open app.py
in your text editor and start by importing FastAPI
from fastapi
:
from fastapi import FastAPI
Next, create an instance of FastAPI
and define a simple endpoint:
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
In this example, we define a single endpoint that returns a JSON object with the key "Hello" and the value "World".
Step 5: Run your FastAPI app
To run your FastAPI app, use Uvicorn in the terminal:
uvicorn app:app --reload
This command tells Uvicorn to run the app
instance in the app.py
file, and the --reload
flag automatically reloads the server when code changes are made.
Step 6: Test your API
Open your web browser and navigate to http://localhost:8000
to test your API. You should see the JSON response with the "Hello" key and "World" value.
Step 7: Add more endpoints
You can add more endpoints to your FastAPI app by defining additional functions with the @app.get
or @app.post
decorators. For example:
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
In this example, we define an endpoint that takes an item_id
parameter and an optional q
query parameter.
Step 8: Run your app with multiple workers
FastAPI allows you to run your app with multiple workers using Uvicorn. To do this, add the --workers
flag to the Uvicorn command:
uvicorn app:app --reload --workers 4
This command tells Uvicorn to run the app with 4 workers, which can help improve performance and handle more concurrent requests.
Congratulations! You have successfully built a demo API using FastAPI. FastAPI provides many additional features and tools for building robust APIs, so be sure to check out the official documentation for more information and examples.