0
0
FastAPIframework~30 mins

Why databases persist data in FastAPI - See It in Action

Choose your learning style9 modes available
Why Databases Persist Data
📖 Scenario: You are building a simple FastAPI app to store and retrieve user notes. This app will show how data is saved persistently using a database instead of temporary memory.
🎯 Goal: Create a FastAPI app that saves notes in a dictionary and then add a configuration to simulate saving notes persistently. Finally, implement a route to add notes and a route to get all saved notes.
📋 What You'll Learn
Create a dictionary called notes_db to store notes with keys as note IDs and values as note texts
Add a variable called next_id starting at 1 to assign unique IDs to notes
Write a POST route /add_note that accepts a note text and saves it in notes_db with the current next_id, then increments next_id
Write a GET route /notes that returns all saved notes from notes_db
💡 Why This Matters
🌍 Real World
Many web apps need to save user data like notes, messages, or profiles so it stays available after the app restarts or users come back later.
💼 Career
Understanding how to persist data is essential for backend developers building APIs and services that manage user data reliably.
Progress0 / 4 steps
1
Create the initial data structure
Create a dictionary called notes_db initialized as empty and a variable called next_id set to 1 to hold note IDs.
FastAPI
Need a hint?

Use notes_db = {} to create an empty dictionary and next_id = 1 to start IDs from 1.

2
Add configuration variable
Add a FastAPI app instance called app by importing FastAPI and creating app = FastAPI().
FastAPI
Need a hint?

Import FastAPI and create an app instance with app = FastAPI().

3
Implement core logic to add notes
Write a POST route /add_note using @app.post("/add_note") that accepts a JSON body with a text field. Inside the function, add the note text to notes_db with the current next_id as key, then increment next_id by 1. Return the note ID in the response.
FastAPI
Need a hint?

Use @app.post("/add_note") decorator and an async function that reads JSON from the request. Use global next_id to modify the variable.

4
Add route to get all notes
Write a GET route /notes using @app.get("/notes") that returns the entire notes_db dictionary.
FastAPI
Need a hint?

Use @app.get("/notes") decorator and return the notes_db dictionary directly.