In this tutorial, you will learn how to make a REST API using FastAPI a Python framework.
This includes.
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.
First of all – what is an API (Application Programming Interface)?
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.
A 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.
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?
Some common practices in REST APIs are.
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.
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.
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.
We see the project contains some files.
We will shortly explore them.
Just to note, the venv folder contains the virtual environment and you should ignore the content in it.
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.
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.
It tells Git which files to ignore when committing to your project. For the most part, you can ignore the file as well.
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.
This script calls the API.
That is, when the API is running, you can use this script to call the API.
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.
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.
Get the easiest skill set for a Python developer that will get you hired.
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.
Project Description The Fibonacci sequence is as follows. 0 1 1 2 3 5 8…
How ELIZA works? It looks for simple patterns and substitutes to give the illusion of…
Project Description The program you write can do 4 things. It can show the content…
Project Description You will start to sell items from your awesome store. You count items…
Project Description Create a converter from Fahrenheit to celsius using the formula °𝐶=(°𝐹−32)×5/9 Project Prompt…
Project Description Leet (or "1337"), also known as eleet or leetspeak, is a system of…