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 main.py
file. From here lets roll.
from fastapi import FastAPI
app = FastAPI()
# Project root endpoint
@app.get('/')
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
@app.get('/')
async def root():
return {'Message': 'Welcome to my Songs Library'}
@app.get('/songs')
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.
http://127.0.0.1:8000/docs
If you click on the drop down menu and click on execute you shall be in a position to see our dummy 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
@app.get('/song/{song_id}')
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
@app.post('/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.
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
@app.post('/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.
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:
@app.delete('/song/{song_id}')
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
Conclusion
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.