5 Steps to Create a REST API with Python using FastAPI

How to Create Your First REST API with Python

In this tutorial, you will learn how to make a REST API using FastAPI a Python framework.

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 APIs (REpresentational State Transfer).

If you google it, you will probably hear about some principles it needs to fulfill. Also, there is a 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.

What is an API?

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.

APIs are an awesome invention. They can also be thought of as a contract between software modules. Let’s say modules 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.

What is a REST API?

REST API has some additional restrictions.

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

That means a few things.

  • REST API is a client-server architecture. Like a browser (client) and a web server.
  • REST API has a URI and it is like a web server 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 junior developers think they need to understand all these concepts (like REST API) in detail. In reality, most vaguely use these concepts and most seniors would not be able to tell all the design principles behind them.

What is the most important part of 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. The 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 APIs are.

  • JSON. Most REST APIs 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. Commonly, the paths defining the endpoints are nouns.

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

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 diving 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 the previous step.

.gitignore

It tells Git which files to ignore when committing to 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 implemented using a single file, I wanted to show you how an API could be structured in a bigger project.

Why FastAPI?

We could use other frameworks, but FastAPI is 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 that sets up the REST API. Notice that the name, version, and description is set in the app, then it includes a route (we will explore that afterward), 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 the 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 that sets it up, so you don’t need to remember any command lines.

If you run

python server.py

Then the server will 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.

You can learn how to add Loggin here.

How to get a job as Python developer without wasting time learning the wrong skillset

Get the easiest skill set for a Python developer that will get you hired.

  • Learn the secrets of how to create production code that is easy to monitor, which means you don’t get a call in the middle of the night because your service broke down.
  • Create REST APIs as microservices, this makes your code easy to understand and will make you look like a senior programmer.
  • Focus on the skills that are actually needed and not waste time to learn advanced Algorithms and Data Structures, which you will never use as a professional Python developer.

Having a Python REST API cloud skillset will get you a job.

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

Learn Python

Learn Python A BEGINNERS GUIDE TO PYTHON

  • 70 pages to get you started on your journey to master Python.
  • How to install your setup with Anaconda.
  • Written description and introduction to all concepts.
  • Jupyter Notebooks prepared for 17 projects.

Python 101: A CRASH COURSE

  1. How to get started with this 8 hours Python 101: A CRASH COURSE.
  2. Best practices for learning Python.
  3. How to download the material to follow along and create projects.
  4. A chapter for each lesson with a descriptioncode snippets for easy reference, and links to a lesson video.

Expert Data Science Blueprint

Expert Data Science Blueprint

  • Master the Data Science Workflow for actionable data insights.
  • How to download the material to follow along and create projects.
  • A chapter to each lesson with a Description, Learning Objective, and link to the lesson video.

Machine Learning

Machine Learning – The Simple Path to Mastery

  • How to get started with Machine Learning.
  • How to download the material to follow along and make the projects.
  • One chapter for each lesson with a Description, Learning Objectives, and link to the lesson video.

Leave a Comment