How to perform CRUD functionalities on FastAPI App

In this tutorial we are going to learn how to perform Create, Read, Update and Delete operations in a FastAPI application. In our previous post, we saw how to install and create the first application using RESTful FastAPI.

In this tutorial we will create an API to fetch your favorite songs from the database. We will be implementing the database using the MYSQL.

Run CRUD operations

To begin with, lets first create a project folder. Inside this project lets install fastapi and uvicorn server.

mkdir songs
cd songs
pip install fastapi
pip install "uvicorn[standard]"

Open the songs folder with your favorite code editor and create file. From here lets roll.

from fastapi import FastAPI

app = FastAPI()

# Project root endpoint
async def root():
    return {'Message': 'Welcome to my Songs Library'}

Fetch all songs(GET)

I want to get all the movies from the database, therefore before we can implement fully fletched database, we will use a dummy database.

from fastapi import FastAPI

app = FastAPI()
#Dummy database
songs = [ {"title":"", "Artist":"", "year":0},#empty dictionary for easy logic implemetation in retrieving songs from db
    {"title": "Good bye", "Artist": "Cellin dion", "year": 2000},
    {"title": "Ali maccaine", "Artist": "mike robson", "year": 2008},
    {"title": "God yo are good", "Artist": "Jesus alive ministries", "year": 2020},
    {"title": "Chop that shit", "Artist": "Black eyepees", "year": 2022},
    {"title": "come home", "Artist": "Ricky", "year": 2023},

# Project root endpoint
async def root():
    return {'Message': 'Welcome to my Songs Library'}

def get_ll_Songs():
    return songs

In the above code, we have populated a database with fake figures to help us work on the project before we can implement the MYSQL database. Now go to the swagger docs to test your first endpoint.
Nextgentips: List all songs
Nextgentips: List all songs

If you click on the drop down menu and click on execute you shall be in a position to see our dummy data.

Nextgentips: All db data
Nextgentips: All db data

Retrieve one song(GET)

Whenever you want to retrieve a single song from the database, you need to implement code like below example.

# Retrieve a single song
def get_one_song(song_id:int):
    return songs[song_id]

Create a song(POST)

The next thing is to create a song into the database. Create is the first letter from CRUD operations. Use the following code to create a record into the database.

# Create a song'/song')
def create_song(song:dict): # pass the dictionary from the dummy data
    songs.append(song) # append the created song to the end of the array
    return {'message': 'Song successfully created'}

You will be in a position to see your return message from the swagger UI or go to list all songs to confirm if the data was created.

Nextgentips: Create success message
Nextgentips: Create success message

Updating a song(PUT)

Whenever we want to update a song, we can use PUT to accomplish that, sometimes we want to update a bit of the data, then we can use PATCH. For this example I will still use POST request then when I have implemented the full database then I will choose to use PUT.

# Update a song'/update_song')
def update_song(song_id:int, song:dict):
    updated_song = songs[song_id]# get a song from array of songs
    updated_song['title'] = song['title']
    updated_song['Artist'] = song['Artist']
    updated_song['year'] = song['year']
    songs[song_id] = updated_song
    return  updated_song, {'message': "The song has updated successfully"}

Success message after doing the update.

Nextgentips: Update success message
Nextgentips: Update success message

Delete a song(DELETE)

Deleting an item from the database only requires a id of what you want to delete. To delete the song from our array, use the following code:

def delete_song(song_id:int):
    songs.pop(song_id)# python pop method to remove an item
    return {'message': "The song has been deleted successfully"}

The following is the success message

Nextgentips: Delete success message
Nextgentips: Delete success message


We have successfully implemented the CRUD functionalities using the dummy array data. next we will see how to implement this using data from the real database with the use of SQLAlchemy.

About Kipkoech Sang

I am a technology enthusiast who loves to share gained knowledge through offering daily tips as a way of empowering others. I am fan of Linux and all other things open source.
View all posts by Kipkoech Sang →

Leave a Reply

Your email address will not be published. Required fields are marked *