Sitemap
Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Photo by Lauren Mancke on Unsplash

Introduction

10 min readNov 28, 2022

--

FastAPI is gaining huge popularity in the devs community right now due to how fast it performs compared to all other python frameworks. Not only that but it also provides a great editor support and way faster development time compared to the older web frameworks. FastAPI gives a huge flexibility while choosing what tools you want to use much like what Flask does, which might be a little bit overwhelming for new comers to web development, but I think it’s worth it taking in mind how well it performs in scalable applications and all the benefits we just mentioned. So without further ado, let’s find out how to start using FastAPI.

Prerequisites

  1. Basic web development knowledge.
  2. Python basics.
  3. Python installation on your machine.

Installation

The first thing we need to do to get started is to install FastAPI and its dependencies, you can do this with one simple command:

poetry add "fastapi[all]"

This command installs fastapi along with its dependencies like uvicorn which is an ASGI webserver. You’re probably wondering what is poetry, it’s simply a dependency management tool similar to pipenv, but I like poetry better because it’s more elegant and it can be used in publishing a package too. You can read more about poetry through their official web page and same goes for pipenv you can visit their official web page here. Here’s a comparison between all the package management tools used in python recently.

First Endpoint Implementation

In your project’s root create a main.py which will be the entry point to your application and we can create our first endpoint as simple as adding this snippet of code to your main.py:

from fastapi import FastAPI


app = FastAPI()


@app.get("/first-endpoint")
async def root():
return {"message": "Hello World"}

This is a very simple `get endpoint` as you can see returns a JSON object that contains a “message” key holding the string “Hello World”. Let’s break it down:

  1. first we define app = FastAPI() which will be the entry point to our whole application.
  2. We define a function that will be called when someone visits our endpoint, in our case we implemented a function that only returns a simple JSON object containing a welcome message. Don’t worry about the async keyword for now, it means that this function is asynchronous but it doesn’t matter in this case.
  3. The decorator used on the function is defining a path operation, it takes as an argument the endpoint’s path which in this case is /first-endpoint , once someone visits this path, the root function will be executed. If you’re not familiar with what a decorator is, it’s simply another function that we use to wrap the function we’re writing to add some extra behaviour to it. You can read more about decorators in this great extensive article.
  4. In this endpoint we used app.get which marks the endpoint as a get endpoint. We can use other functions as decorators like app.post or app.put for example, each function corresponds to an HTTP Method.
  5. Now to run the application open a command line window and write the following command:
    uvicorn main:app --reload
    This tells uvicorn that our entry point is a variable called app and it can be found in a file called main, the --reload is a flag telling it to reload the server on any change.
  6. Now if you go to localhost:8000/first-endpoint you will find the hello world greeting message there, and if you go to localhost:8000/docs you will find Interactive documentation auto generated by Swagger UI, you can also find an alternative documentation if you go to localhost:8000/redoc . You don’t need to do anything for this to happen, all what you need to do is define your endpoint and FastApi already takes care of everything else for you.

What we are going to build

Now that we saw how we can implement a very basic endpoint with FastAPI using just a few lines of code, let’s start exploring the things that FastAPI allows us to do with the same simplicity and elegance, to do that we are going to build a simple To-do app using FastAPI. At the end of the article we should have a small app capable of adding a new to-do, fetch all your to-dos or a single to-do only, and delete a to-do.

If you want to check out the final result you can find it here in this github repository.

Initial setup

To start off our application, let’s start with creating the app entry point like we did before, create a fake database where we are going to store our to-do items and then implement the simplest endpoint in our app, a GET endpoint responsible for listing all the items found in our fake database.

  1. Create a list to act as a fake database and populate it with dictionaries where each one represents a to-do item:
from fastapi import FastAPI


app = FastAPI()
ITEMS = [
{
"id": 1,
"title": "Learn FastAPI",
"description": "Learn how to use all the cool features found in FastAPI",
},
{
"id": 2,
"title": "Buy food",
"description": "Buy some food on your way home because you have no time to cook today, you have to learn FastAPI",
},
]

2. Define the path operation or the endpoint that’s going to serve the list of to-do items in our database:

@app.get("/items/")
async def get_items():
return ITEMS

We define the path operation using the app.get decorator and we tell FastAPI the path to our endpoint by passing the string “/items/” to the decorator, when this path is requested please execute the decorated function below, which in this case is get_items. In the function’s body we simply return the items list. Now if you go to localhost:8000/docs and try the endpoint out, you will find it returning the list of items as we expected.

If you don’t know what decorators work you can read about them more here, they are basically some python magic that changes the way a function behaves without modifying its structure.

Path Parameters

Let’s say for some reason we want our API to serve a single to-do item instead of all the items that we have, for this purpose we have to implement a different endpoint that uses an item’s id field to retrieve it, but how exactly are we going to tell FastAPI please fetch me the item with this id ? This is where “path operations” come into play, we are going to pass the id inside the endpoint’s path, and we can do it like this:

@app.get("/items/{item_id}")
async def get_item(item_id: int):
return ITEMS[item_id - 1]

This endpoint is fairly similar to the endpoint fetching all the items in the database, except for one small change. You can see in the path passed to the app.get decorator that we added {item_id} inside the string, which is a similar syntax to what python f-strings use. We then add an argument item_id of type int to the function executing our endpoint’s logic. This way when we go to for example /items/1 FastAPI knows that it has to call get_item and pass it item_id=1 . In the function’s body we use the item_id as an index for the ITEMS list just for the sake of simplicity.

Now if you go to localhost:8000/docs you will find the endpoint is well documented, what type of parameters it expects. If you try to request the endpoint with a string item id like this /items/foo you will receive a validation error that it must be of type integer, this happens because we added type annotation to the item_id argument in the endpoint.

Try it out with one of the ids that exists in our database, we didn’t handle the case of ids that don’t exist in the database just for the sake of simplicity, in another article we are going to connect an actual database, and we will do it there, it’s going to be more relevant to the topic of the article.

Get Abdelrahmen Ayman’s stories in your inbox

Join Medium for free to get updates from this writer.

So you also get automatic validation with just using type hints which is by the way something you should do, it makes your life a lot easier on the long run, Believe me !

Pydantic Models

In order to proceed with the rest of the tutorial, we will have to get introduced to Pydantic. I think that the definition provided by the people who made Pydantic is the best way to introduce it to you:

Data validation and settings management using Python type annotations. pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.

Now that we know what Pydantic is, we can proceed to the following step. The next endpoint we are planning to implement is a POST endpoint that adds a new to-do item, and to do that we will have to accept user input, and of course we need to validate this data and that’s what pydantic is going to help us with.

To add a new item you need to provide a title and a description, we can force this structure by defining a schema or what pydantic calls a model:

from pydantic import BaseModel


class BaseTodoItem(BaseModel):
title: str
description: str

By inherting from pydantic’s BaseModel we now have our custom model. Next we start defining fields that we want the user to send to our endpoint and define their type using python type hints. From this simple implementation, pydantic is going to detect that title and description are required fields and their respective types are string and string.

By using BaseTodoItem with any data we can start validating this data, for instance try running BaseTodoItem(title="some title") you will get a validation error stating that description field is required but found missing.

Request Body

Now that we have the data validation part implemented, let’s actually implement the add item endpoint and use the data validation model in that endpoint. As we did with the GET endpoints we are going to use app.post decorator to indicate a POST endpoint, it will also have the path /items/ :

ITEMS = []

@app.post("/items/")
async def add_item(item: BaseTodoItem):
ITEMS.append(item)
return item

Now what we did here is just passing a new argument item and we gave it the type of the BaseTodoItem that we defined before, using this FastAPI knows that this is meant as a request body, and it doesn’t confuse it with path parameters, because there is no {} found in the path we passed to app.post which is the syntax used to indicate a path parameter in FastAPI.

The item variable holds the request data in the form of python object of type BaseTodoItem which we add to the empty ITEMS list and we return it as a response.

We have a small problem, now our items do not have an id, we need to auto generate our id fields, for the sake of simplicity we’re going to use the item’s index in the list as its own id too :

@app.post("/items/")
async def add_item(item: BaseTodoItem):
item_dict = item.dict()
item_dict.update({"id": len(ITEMS)})
ITEMS.append(item)
return item

To alter the item and add a new field we had to get its dict representation and add the id field to it. But now we are adding a dictionary to the ITEMS list and we are returning a dictionary too, this is bad because we lose the autocomplete privileges that pydantic helps us with. to fix this we are going to create another Pydantic model that accepts an id too, which is going to inherit from BaseTodoItem and we are going to convert the dictionary back to a python object using the new model:

class TodoItem(BaseTodoItem):
id: int


@app.post("/items/")
async def add_item(item: BaseTodoItem):
item_dict = item.dict()
item_dict.update({"id": len(ITEMS)})
modified_item = TodoItem(**item_dict)

ITEMS.append(modified_item)
return modified_item

With this we get data validation for request body before assigning it to the item variable and we also get auto complete features for the item object thanks to pydantic.

Response Model

Now our application is working fine but we have a final touch to add. The documentation now has no idea what our response is supposed to look like, to solve this problem we can use another feature that FastAPI provides with the help of pydantic which is response models.

Add an argument to the endpoint decorator called response_model and assign it the TodoItem pydantic model we defined earlier, which is also the type of the object we’re returning from our endpoint, FastAPI is going to use this pydantic model in auto generating the docs for you. and the final code should look like this:

from fastapi import FastAPI
from pydantic import BaseModel


app = FastAPI()

ITEMS = []


class BaseTodoItem(BaseModel):
title: str
description: str


class TodoItem(BaseTodoItem):
id: int


@app.get("/items/{item_id}", response_model=TodoItem)
async def get_item(item_id: int):
return ITEMS[item_id]


@app.get("/items/")
async def get_items():
return ITEMS


@app.post("/items/", response_model=TodoItem)
async def add_item(item: BaseTodoItem):
item_dict = item.dict()
item_dict.update({"id": len(ITEMS)})
modified_item = TodoItem(**item_dict)

ITEMS.append(modified_item)
return modified_item

The add_item endpoint request body has BaseTodoItem as a type because we don’t want the user to send us the id and this model doesn’t require the user to provide one, while when returning the item we want to show the user the item’s id so that he can use it in fetching the item later.

What’s Next ?

I am planning on making this like a small series about FastAPI, the next article should include some other FastAPI features like connecting our application to a real database and using an ORM like sqlalchemy and migrate that database using alembic.

Conclusion

We saw how we can very quickly with a single python file implement a simple to-do web app application using FastAPI framework. We explored how we can define path operations and how to use the auto generated documentation for the endpoints provided by FastAPI. We also explored some of the basic web concepts and how FastAPI implements them like adding path parameters and handling request body how we can help the documentation with what the response structure should look like.

You can always read more on your own if you feel like in FastAPI documentation, it’s very well written and it’s a great place to start learning FastAPI.

I hope you enjoyed this article, if you have any questions or anything that you’d like to share with me, please feel free to leave a comment in the comments section or reach out to me using any of my social media accounts,

Cheers

References:

  1. Poetry Home: https://python-poetry.org/
  2. Pipenv Home: https://pipenv.pypa.io/
  3. Package managers comparison: https://remaster.com/blog/pip-pipenv-poetry-comparison
  4. Decorators Article: https://realpython.com/primer-on-python-decorators/
  5. Project Repo: https://github.com/abdelrahmenAyman/How-to-create-a-simple-FastAPI-app
  6. Pydantic docs: https://pydantic-docs.helpmanual.io/
  7. FastAPI docs: https://fastapi.tiangolo.com/

--