This code sets up a FastAPI application and initializes three
dictionaries (users_db, products_db, and orders_db) to store
data. The dictionaries are typed to ensure they hold specific data
structures: users_db stores user data, products_db stores
product data, and orders_db stores order data. These dictionaries,
are intended to be used as a basic in-memory database for the
FastAPI application.
+ Python3
Python3
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Dict
app =FastAPI()
users_db: Dict[int, User] =()
products_db: Dict[int, Product] ={}
orders db: Dict[int, Order] =}
Step 5: Creating the Endpoints
Create endpoints for all operations performed by the API. Here's an
example of how to add a new user.
This code defines a FastAPI endpoint at “Jusers/” that allows users
to create new user records. When a POST request is made with
user data in the request body, a unique user ID is generated, and
the user's data is stored in the “users_db” dictionary. The
response includes the assigned user ID and the user's data in the
specified format.
+ Python3
Python3
@app.post("/users/", response_mode!
async def create user(user: User)
user_id =len(users_db) +1
users_db[user_id] =user
return {"user_it
user_id, **user.dict())
Step 6: Creating the FastAPI Applic:
Finally, add this code to the end of main.py to run the FastAPI app.
This part of the code runs the FastAPI application using UVicom, a
lightweight ASGI server. Itistens on all available network interfaces
0.0.0.0") and port 8000. When this script is executed, the FastAPI
application becomes accessible on that host and port.
Python
Python3
if _name_ =="_main
import uvicorn
uvicorn.run(app, host="0.0.0.0*, port=8000)
STEP 7: Test the API, run the FastAPI app using the following
‘command:
luvicorn main:app -reload
Sending a POST request
username”: “john_doe",
‘email’:
[email protected]”