Creating a Basic RESTful API with FastAPI in Python

Posted by


In this tutorial, we will go through the process of building a simple REST API using FastAPI in Python. FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is fast, easy to use, and highly efficient. We will create a simple API with basic CRUD operations for a fictional "todo" application.

Step 1: Setting up the Environment

First, make sure you have Python installed on your machine. You can download and install Python from the official website (https://www.python.org/). Next, create a new directory for your project and navigate to it in your terminal.

To create a new virtual environment, run the following command:

python -m venv env

Activate the virtual environment by running the appropriate command for your operating system:

For Windows:

.envScriptsactivate

For MacOS/Linux:

source env/bin/activate

Install FastAPI and Uvicorn (ASGI server) using pip:

pip install fastapi uvicorn

Step 2: Creating the API

Create a new Python file, for example, main.py, and import necessary modules:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

Define the data model for a todo item using Pydantic:

class TodoItem(BaseModel):
    id: int
    title: str
    description: str
    done: bool

Now, let’s create a list to store todo items:

todo_list = []

Create API routes for CRUD operations:

@app.get("/todos")
def get_all_todos():
    return todo_list

@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
    for todo in todo_list:
        if todo["id"] == todo_id:
            return todo
    return {"error": "Todo not found"}

@app.post("/todos")
def create_todo(todo: TodoItem):
    todo_dict = todo.dict()
    todo_list.append(todo_dict)
    return todo_dict

@app.put("/todos/{todo_id}")
def update_todo(todo_id: int, todo: TodoItem):
    for index, item in enumerate(todo_list):
        if item["id"] == todo_id:
            todo_list[index] = todo.dict()
            return {"message": "Todo updated"}
    return {"error": "Todo not found"}

@app.delete("/todos/{todo_id}")
def delete_todo(todo_id: int):
    for index, item in enumerate(todo_list):
        if item["id"] == todo_id:
            del todo_list[index]
            return {"message": "Todo deleted"}
    return {"error": "Todo not found"}

Step 3: Running the API

To run the API, use the following command:

uvicorn main:app --reload

You can now access the API endpoints on http://localhost:8000/docs to interact with the API using the Swagger UI. You can test the CRUD operations for todo items by sending requests to the appropriate endpoints.

That’s it! You have successfully built a simple REST API using FastAPI in Python. FastAPI makes it easy to create APIs with Python, providing built-in validation, automatic documentation generation, and high performance. There are many more features and capabilities of FastAPI that you can explore to build complex APIs for your applications.

0 0 votes
Article Rating
29 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jacobwilsonmwale1674
1 month ago

amazing tutorial👏👏. It has helped me understand a lot about fastapi. cheers mate🥂

@RohitSaini-t4r
1 month ago

your intro is nice

@hfrog713
1 month ago

does anyone know if there is a way to take the ID out of the sample when you "Try It out" since we are not assigning it back. I find it pretty confusing.

@hfrog713
1 month ago

Also, for everyone….

Is there not a more efficient way of doing this?

def search_provider(accepting: Optional[int] = Query(None, title="Accepting", description="Is the Doctor accepting new patients?"),

gender: Optional[str] = Query(None, title="Gender", description="Gender of the Doctor")):

accepting_providers = [p for p in providers if accepting.lower() == p['accepting']]

if gender is None:

if accepting is None:

return providers

else:

return accepting_providers

else:

gendered_providers = [p for p in providers if gender.lower() in p['gender']]

if accepting is None:

return gendered_providers

else:

combined_condition = [p for p in accepting_providers if p in gendered_providers]

@hfrog713
1 month ago

is that a chrome extension for your json viewing?

@freepythoncode
1 month ago

Thank you so much 🙂❤

@Sam-tg4ii
1 month ago

Thanks for the great explanation. I have one question. Imagine I have the data and the API code on a raspberry pi as a server. How can I give a client access to it over the internet? I mean, I need the client to be able for example to fetch data (get) either using the header method or preferrably the FastAPI's documentation interface that you showed here. Thanks

@user-db2ug8tr5o
1 month ago

I believe that you didn't consider problem with ID after deletion. If you remove something from the middle you will get bad indexes. Anyway thx for this video I find it's really useful.

@Nicolas_Rangel
1 month ago

Fix for add_person():

people.append(new_person)

people_write = {"people": people}

with open("people.json", "w") as f:

json.dump(people_write, f)

@apraveena
1 month ago

Great tutorial, Thank you so much. I feel so confident in REST API now 🙂

@pepecopter
1 month ago

thanks that was great!

@sushmita3537
1 month ago

just in case anyone's getting a TypeError: Object of type Person is not JSON serializable at add_person(), you need to do this json.dump(dict(people), f)

@MorrasAI
1 month ago

Dude this was fantastic ! Great Job.

@user-zlcksu4asdv
1 month ago

Man, exactly what I was looking for. Implemented what I wanted in 5 minutes "while" watching your video! Thanks heaps!

@FreakyStyleytobby
1 month ago

Great tutorial man, im grateful for your work here. Really concise vid.

@pedromiranda3148
1 month ago

I there!!! Great videos and great work. Just dropping suggestion of similar video with Django Rest library

@vikashvashishat4011
1 month ago

Hi! can you plz help to use postgres for data for the same

@buixuanhung8273
1 month ago

i see your json file has been changed when you do add_person() part. I think you should change the code where you call people, you have to change it to people["people"] .

@andrewmenshicov2696
1 month ago

i liked the tutorial but i think some of the code coulda been more thought through, like adding proper guard clauses, doctsrings and less ugly id usage 😅😅

@zakyvids6566
1 month ago

Hey there Just came across your channel and started learning python recently

Was wondering After completing this playlist

Should I move on to projects or learn more concepts

https://youtube.com/playlist?list=PL7yh-TELLS1E6dNCzfQl-NG-KJP3C-4mc