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

Leave a Reply

32 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@fuadmubtasim
27 days ago

Walaikum as-salam

@Ukkashatu
27 days ago

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

@kirubababu9255
27 days ago

Could you please post a Quart API tutorial

@andrastamasmagyar3731
27 days 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
27 days ago

Look, a transphobe. How refreshing

@jyoun79
27 days 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
27 days ago

How to apply that certificate you advised?

@user-hf8iy8xp9y
27 days ago

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

@rayarezzan974
27 days ago

you are ammmmmmmaaaazing

@mouhannadal-hmedi1501
27 days ago

what the amazing "Asallamulikum" bro 😂❤

@AR-co7gd
27 days ago

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

@claytonvanderhaar3772
27 days ago

Great tutorial only thing for me was Optional was not working

@hygosousa1170
27 days ago

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

@lapislazuli1949
27 days ago

where's put?

@ashwathiv8183
27 days ago

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

@dlouise64
27 days ago

Thank you 🙂

@Fosdark
27 days ago

Thank for video!

@Fadylineage
27 days ago

Great Video brother.

Terminal:
if it didn't work using

uvicorn main:app –reload

use

python -m uvicorn main:app –reload

@primrose1491
27 days 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
27 days ago

which font do you use? seems very clean.

32
0
Would love your thoughts, please comment.x
()
x