5 Steps to Create a REST API with Python using FastAPI

What will we cover?

In this tutorial we will learn how make a REST API using FastAPI

This includes.

  • What is a REST API
  • How to install the requirements
  • Structure of files
  • How to add an endpoint to the REST API
  • How to run and test it

Step 1: What is a REST API?

You have probably heard about REST API’s (REpresentational State Transfer).

If you google it, you will probably hear about some principles it needs to fulfill. And yes, there is the formal definition, but for me it seems difficult to translate the formal definition into something you understand is a REST API.

Let’s think about it differently.

First of all – what is an API (Application Programming Interface)?

  • It enables software or modules in software to talk to each other.
  • It doesn’t have to be the same programming language.

Actually, API’s are an awesome invention. They can also be thought of a contract between software modules. Let’s say module A and B communicate (or talk) with each other through a specified API. Then you can change a module, say module B, if it still follows the API. This makes the software easier to maintain.

REST API has some additional restrictions.

When most talk about REST API’s they mean a web API where they can send HTTP verb and a URL (or URI) which describes the location of the resource.

That means a few things.

  • REST API is a client-server architecture. Like a browser (client) and webserver.
  • REST API has a URI and it is like a webserver with different pages or resources.
    • URI (Uniform Resource Identifier) is a unique sequence of characters to identify a resource (like a web server, REST API, or similar).

Funny note: Most juniors developers think they need to understand all these concepts (like REST API) in detail. In reality, most use these concepts in a vague manner and most seniors would not be able to tell all the design principles behind them.

What is the most important part about a REST API?

  • Stateless. That means the server does not know what you just have done – you need to kind of explain everything in every call you do. This makes the server logic easy – it does not need to check any history or state from the caller (or client), it knows exactly what to do from the path and parameters.
  • HTTP verbs. A REST API uses HTTP request methods. Most common are.
    • GET. Retrieves resources.
    • POST. Submits new data to the server.
    • PUT. Updates existing data.
    • DELETE. Removes data.

Some common practices in REST API’s are.

  • JSON. Most REST API use JSON to transfer the request and answers.
    • JSON (JavaScript Object Notation) is an open standard format for data exchange in a human-readable format. It is widely used and not limited to JavaScripts, as the name suggests.
  • Paths names are nouns. It is common that the paths defining the endpoints are nouns.

On this journey we are on, we will create simple resources and expose them as REST API’s.

We will only have endpoints (paths) that we use – this ensures we have a simple interface and focus on what matters to learn what we intend.

Let’s get started with our first simple REST API.

Step 2: Clone and install requirements

The easiest way to get started is by Cloning an existing structure of a project and dive into it. You will be surprised how easy it is after some inspection.

The easiest way to clone a project is to use an IDE like PyCharm.

But you can also do it from the command line in a terminal with the following command. Note that you need git installed.

git clone https://github.com/LearnPythonWithRune/fruit-service.git

This will clone this repository in a folder called fruit-service where you are located in the terminal.

Then you need to install the requirements, but before that it is a good idea to create a virtual environment.

Go to the folder of the newly cloned repository.

cd fruit-service

Now you should be located in the newly cloned repository (after executing the above command). Then create a virtual environment for Python.

python -m venv venv

This creates a virtual environment, now you need to activate it (which depends on the operating system).

If on Unix or Mac:

source venv/bin/activate

If on Windows

Scripts\activate.bat

NOTICE If you use PyCharm all of this is done for you when you create a new project. This is what makes your life easier and you don’t need to bother with all of this.

Now you need to install the requirements.

Take a look at the requirements.txt file.

uvicorn==0.17.5
fastapi==0.75.0
requests==2.27.1

This is a list of all the libraries we will use in the project.

  • uvicorn is the server to run the REST API.
  • fastapi is the framework we write the code for our REST API
  • requests we use to make Python script to call our REST API

To install all the libraries execute the following command in the virtual environment we have created.

pip install -r requirements.txt

Now we are ready to start.

Step 3: Explore the files in the project

We see the project contains some files.

  • README.md
  • requirements.txt
  • .gitignore
  • server.py
  • make_order.py
  • app/main.py
  • app/routers/order.py

We will shortly explore them.

Just to note, the venv folder contains the virtual environment and you should ignore the content in it.

README.md

The README.md is an essential guide that gives other developers a description of your GitHub project. It is written in Markdown, which is a lightweight markup language for creating formatted text using a plain-text editor.

We will not explore this file further. Simply, think of it as a description for others to understand the project.

The detail level can vary a lot, as you see here.

requirements.txt

This file is essential – it contains a list of the libraries that are needed by the project. We already installed them in previous step.

.gitignore

It tells Git which files to ignore when committing your project. For the most part, you can ignore the file as well.

The files: server.py,  app/main.py, and app/routers/order.py

These files are the basis for the REST API we will run in a moment. They are all connected together and use the FastAPI Python framework.

While the API is very simple, and could be implement using a single file, I wanted you to show you how an API could be structured in a bigger project.

Why FastAPI?

We could use other frameworks, but FastAPI is a simple to learn and understand.

In a moment we will explore it further.

make_order.py

This script calls the API.

That is, when the API is running, you can use this script to call the API.

Step 4: Explore the REST API code

First let’s look at the code in app/main.py

from http import HTTPStatus
from fastapi import FastAPI

from app.routers import order

app = FastAPI(
    title='Your Fruit Self Service',
    version='1.0.0',
    description='Order your fruits here',
    root_path=''
)

app.include_router(order.router)


@app.get('/', status_code=HTTPStatus.OK)
async def root():
    """
    Endpoint for basic connectivity test.
    """
    return {'message': 'I am alive'}

This is the main file which sets up the REST API. Notice that the name, version, description is set in the app, then it includes a route (we will explore that afterwards), then it adds a GET endpoint (the default one).

This default endpoint (called root()) does not really have any functionality. It is common practice to have one endpoint like that. The reason is to have another service calling it all the time to test if it is alive. This makes it easy to monitor if the service (the REST API) is running.

Now let’s get back to this.

app.include_router(order.router)

This adds a router to our app. This router is located in the file app/routers/order.py (you can see that from the import statement).

Let’s explore that file.

from http import HTTPStatus
from fastapi import APIRouter

router = APIRouter()


@router.post('/order', status_code=HTTPStatus.OK)
async def order_call(order: str):
    print(f'Incoming order: {order}')
    return {'order': order}

In a REST API you would place all the endpoints in the subfolder app/routers/ as this one.

You can see that it contains a router (path) of a post-call (remember the types defined in step 1) order. This call takes one argument order of type str (string).

This endpoint does not do much, it will print a statement to the terminal where it is running and return the json data {‘order’: order}, where order is the incoming argument.

Now it is time to try the REST API.

Step 5: Running and calling our REST API

There are multiple ways to run the REST API, here we have created a server.py file which sets it up, so you don’t need to remember any command lines.

If you run

python server.py

Then the server sill start.

You can call it from the Swagger docs on your local host: http://127.0.0.1:8000/docs

From here you can call it by expanding the /order and type in banana as shown here.

Then press the blue Execute. This should result in output in your terminal where you run your server.

Using the Swagger docs interactively like this, is a great way to manually test the REST API.

In case you wonder, the Swagger docs are generated automatically by the FastAPI framework.

If you want to have a Python script to call your REST API then look at the make_order.py file.

import random
import requests


banana = '🍌'
apple = '🍎'
pear = '🍐'

items = [banana, apple, pear]

# Make a random order
order = items[random.randrange(len(items))]


url = "http://127.0.0.1:8000"

response = requests.post(
    url=f'{url}/order',
    params={
        'order': order
    }
)

print(f'Status code: {response.status_code}, order: {order}')

Run it and see what happens.

Want to learn more?

Get my book that will teach you everything a modern Python cloud developer needs to master.

Learn how to create REST API microservices that generate metrics that allow you to monitor the health of the service.

What does all that mean?

Don’t wait, get my book and master it and become one of the sought after Python developers and get your dream job.

Leave a Reply Cancel reply

Exit mobile version