Tutorial on Building RESTful APIs using FastAPI in Python

Posted by


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.

0 0 votes
Article Rating
32 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@fuadmubtasim
2 months ago

Walaikum as-salam

@Ukkashatu
2 months ago

MashaAllah this is an amazing intro for me. Thanks brother.

@kirubababu9255
2 months ago

Could you please post a Quart API tutorial

@andrastamasmagyar3731
2 months ago

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!! 🙂

@theTrigant
2 months ago

Look, a transphobe. How refreshing

@jyoun79
2 months ago

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

@mugenzideodate5733
2 months ago

How to apply that certificate you advised?

@user-hf8iy8xp9y
2 months ago

very clear explanation with background on HTTP methods and Swagger documentation.
One additional helpful topic would have been query string parameters.

@rayarezzan974
2 months ago

you are ammmmmmmaaaazing

@mouhannadal-hmedi1501
2 months ago

what the amazing "Asallamulikum" bro 😂❤

@AR-co7gd
2 months ago

Very nice video, brother. I only wish you also wrote to PostgreSQL as depicted in the diagram.

@claytonvanderhaar3772
2 months ago

Great tutorial only thing for me was Optional was not working

@hygosousa1170
2 months ago

Thank you so much for you share your know knowledge of a manner so simple and directly.

@lapislazuli1949
2 months ago

where's put?

@ashwathiv8183
2 months ago

can i make single endpoint for different methods like post get delete?

@dlouise64
2 months ago

Thank you 🙂

@Fosdark
2 months ago

Thank for video!

@Fadylineage
2 months ago

Great Video brother.

Terminal:
if it didn't work using

uvicorn main:app –reload

use

python -m uvicorn main:app –reload

@primrose1491
2 months ago

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?

@anindasadman443
2 months ago

which font do you use? seems very clean.