FastAPI is a modern web framework for building high-performance APIs with Python. It is based on standard Python type hints which make it easy to write clear and concise code. In this tutorial, we will learn how to build RESTful APIs using FastAPI.
Prerequisites:
- Basic knowledge of Python programming
- Understanding of RESTful APIs
Installation:
First, we need to install FastAPI and uvicorn, which is an ASGI server that can run FastAPI applications. We can install them using pip:
pip install fastapi uvicorn
Creating a new FastAPI project:
To create a new FastAPI project, first, create a new Python file (e.g., main.py
). In this file, we will define our API endpoints.
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def read_root():
return {"Hello": "World"}
In this code snippet, we have created a new FastAPI app and defined a single endpoint (/
) that returns a simple JSON response.
Running the API:
To run the API, we need to use the uvicorn server. We can start the server by running the following command:
uvicorn main:app --reload
This command will start the uvicorn server and reload the app automatically whenever we make changes to the code.
Visiting http://127.0.0.1:8000/
in your web browser should display the JSON response {"Hello": "World"}
.
Adding more endpoints:
We can add more endpoints to our API by defining new 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}
This endpoint takes an item_id
parameter and an optional q
query parameter, and returns a JSON response with these parameters.
API documentation:
FastAPI provides automatic generation of API documentation using Swagger UI. This documentation is available at http://127.0.0.1:8000/docs
by default. It displays information about the API endpoints, parameters, and responses.
Validation and serialization:
FastAPI supports automatic validation and serialization of request parameters using Python type hints. For example, we can define a request body with specific data types:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post('/items/')
def create_item(item: Item):
return {"name": item.name, "price": item.price}
In this code snippet, we define a Item
class with specific data types for each attribute. When a POST request is made to the endpoint /items/
, FastAPI will automatically validate the request body and deserialize it into an Item
object.
Conclusion:
In this tutorial, we have learned how to build RESTful APIs with FastAPI in Python. FastAPI provides a powerful and efficient way to create APIs using Python type hints. We have covered the basics of creating endpoints, running the API, adding documentation, and handling request validation and serialization. FastAPI is a great choice for building high-performance APIs with minimal boilerplate code.
Walaikum as-salam
MashaAllah this is an amazing intro for me. Thanks brother.
Could you please post a Quart API tutorial
Just a quick comment because it came up as an error in my fastapi version so when you define optional in datebase you have to you field as well, e.g.:
first_name: Optional[str] = Field(None)
Otherwise, amazing contect!! 🙂
Look, a transphobe. How refreshing
For anyone getting an error about the middle_name value, just make sure your model looks like this for the middle_name: middle_name: Optional[str] = None
How to apply that certificate you advised?
very clear explanation with background on HTTP methods and Swagger documentation.
One additional helpful topic would have been query string parameters.
you are ammmmmmmaaaazing
what the amazing "Asallamulikum" bro 😂❤
Very nice video, brother. I only wish you also wrote to PostgreSQL as depicted in the diagram.
Great tutorial only thing for me was Optional was not working
Thank you so much for you share your know knowledge of a manner so simple and directly.
where's put?
can i make single endpoint for different methods like post get delete?
Thank you 🙂
Thank for video!
Great Video brother.
Terminal:
if it didn't work using
uvicorn main:app –reload
use
python -m uvicorn main:app –reload
Thank you for this tutorial, but I think it's not complete since there's no actual database and instead you're using a simple array. And also too many validation errors. Pasting the uuid in each element of the db array is not a solution on my side because I got some ValueError badly formed hexadecimal UUID string.
Can you make a full fastapi tutorial covering more advanced topics of fastapi?
which font do you use? seems very clean.