DEV Community

Cover image for Build Rest API with FastAPI in 3 steps
Prajwal Bhandari
Prajwal Bhandari

Posted on

Build Rest API with FastAPI in 3 steps

This article will explore the detailed tutorial for creating Rest API with FastAPI. FastAPI is the python based framework to create Rest API. According to their documentation.

FastAPI is a modern, fast (high-performance), a web framework for building APIs with Python 3.6+ based on standard Python type hints.

After working on FastAPI in a couple of projects yes I can say that it is fast, very fast due to the async feature in python 3.6+. So it is recommended to use python 3.6+ with FastAPI. There are other features too that make FastAPI developers favorite.

  • Out-of-box API documentation.
  • In-build data validation.
  • FastAPI provides concurrent programming.
  • The minimal robust code base.

For a better understanding and development of the API with FastAPI, I have divided the process into 3 steps. We will achieve each step one by one with better learning and development.

STEP-1: Creation of a virtual environment

There are many tools to create a virtual environment for python but I will be using venv for this tutorial.

venv is a lightweight tool to create an isolated python environment. venv creates a folder that includes all the packages that the python project would use.

First, create a directory for your project. I will be creating a learning directory from the terminal and changing the directory to it.

$ mkdir learning & cd learning

Once we are in our learning directory we can set up our venv. To set up, a virtual environment in our directory run the command

$ python -m venv environment

Above command should create an environment directory inside our learning directory which will contain all the packages for our python project. We have successfully created our virtual environment and to activate it we can run the command.

$ source environment/bin/activate

Once the command is executed without any error message the environment should be activated, then we can proceed to step 2

STEP-2: Setup FastAPI

In this step, we will be creating our first API. Before creating our first API let’s install FastAPI with pip install in our virtual environment.

$ pip install fastapi

Once the FastAPI library has been installed we can create a file main.py. In main.py let’s import the FastAPI library

from fastapi import FastApI

Once the FastAPI is imported we can now create the instance of FastAPI and assigned it to the app variable:

from fastapi import FastApI
app= FastAPI()
Enter fullscreen mode Exit fullscreen mode

The app variable is the main point of interaction to create all APIs. Now let’s define a path operation decorator to define our route path and HTTP method.

from fastapi import FastApI
app= FastAPI()
@app.get('/') #path operation decorator
Enter fullscreen mode Exit fullscreen mode

In the above code, we are creating a GET request with a ’/’ path similarly for POST, PUT, and DELETE we can use the operations:

  • @app.post(‘/’)
  • @app.put(‘/’)
  • @app.delete(‘/’)

To provide the path to our HTTP request, the code should look like this:

@app.get('/custom_path') #path operation decorator
Once the path operation decorator is implemented now we can implement the path operation function:

from fastapi import FastApI
app= FastAPI()
@app.get('/') #path operation decorator
def root():
 return {'message':'Hello world'}
Enter fullscreen mode Exit fullscreen mode

The root() function is called out when the user tries to make a GET request to our path and gets dict as a response. You can also return a list, of singular values such as str, int, etc

The final code in our main.py should be:

from fastapi import FastApI
app= FastAPI()
@app.get('/') #path operation decorator
def root():
 return {'message':'Hello world'}
Enter fullscreen mode Exit fullscreen mode

Now we have created our first API method which should be enough for our 3 steps.

STEP-3: Run the server

Finally, after creating the environment and making our first API we have to run the server. For the server, we will be using uvicorn. Uvicorn is an ASGI web server implementation for Python.

Before using uvicorn we need to install it in our environment.

$ pip install uvicorn

Now once the uvicorn is installed we can start the server with the below command in our terminal:

$ uvicorn main:app - reload

Let’s break down the above command for better understanding.

  • uvicorn is the keyword that triggers uvicorn library
  • The ASGI application should be specified in the form path.to.module:instance.path
  • While using locally we use the --reload flag for hot reload So now we have successfully made the Rest API with FastAPI.

Now go to http://127.0.0.1:8000 in the browser which should give a response like in the screen snippet:

Image description

If we visit http://127.0.0.1:8000/doc we can get the documentation page:

Image description

Finally 🎉, we have developed and served (locally) our first Rest API with FastAPI.

Top comments (0)