How to Create Your First REST API with Python
In this tutorial, we will explore the process of creating a REST API using FastAPI, a powerful Python framework. Throughout this tutorial, you will gain a comprehensive understanding of the essential aspects involved in building a REST API, including:
- What is a REST API: We will begin by delving into the concept of a REST API, understanding its purpose, and exploring its key characteristics.
- Installing the requirements: To get started, you will learn how to set up the necessary requirements and dependencies to work with FastAPI and build your REST API.
- File structure: Understanding the structure of the files comprising a REST API project is crucial for effective development. We will analyze the recommended file structure and discuss the significance of each component.
- Adding endpoints: You will discover how to define and incorporate endpoints into your REST API. We will cover the process of handling various HTTP methods and associating functionalities with each endpoint.
- Running and testing: Finally, you will learn how to execute and test your REST API. We will explore methods to ensure that your API functions as intended, allowing you to validate its behavior and identify potential issues.
By the end of this tutorial, you will have the knowledge and practical experience required to develop your REST API using FastAPI a Python framework, empowering you to build robust and efficient web applications. So, let’s dive in and get started!
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?
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.
- A REST API is a client-server architecture. Like a browser (client) and a web server.
- A 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 typing 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 or explore other aspects of web app development with Python.
Are You a Python Developer Ready to Land Your Dream Job?
Unlock the Key to Success with Cloud, Docker, Metrics, and Monitoring!
Master cloud computing, Docker, logging, Git & GitHub, metrics, and monitoring to accelerate your path to success as a Python developer.
Get job-ready skills without wasting time figuring it out on your own.
Deploy your Python applications effortlessly to the cloud, building scalable and resilient solutions.
Streamline your development workflow with Docker, eliminating compatibility issues and enabling seamless collaboration.
Optimize performance with metrics and monitoring, delivering exceptional user experiences and standing out to employers.
Don't settle for the ordinary. Stand out, impress employers, and supercharge your Python developer career. Buy this eBook now and unlock the power of the cloud, Docker, metrics, and monitoring.
Python for Finance: Unlock Financial Freedom and Build Your Dream Life
Discover the key to financial freedom and secure your dream life with Python for Finance!
Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.
Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.
Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.
Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!
Python for Finance a 21 hours course that teaches investing with Python.
Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.
“Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.
