📜  fast api postgres (1)

📅  最后修改于: 2023-12-03 15:30:44.703000             🧑  作者: Mango

FastAPI Postgres

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. PostgreSQL is a powerful, open-source relational database management system. Combining FastAPI and PostgreSQL can give you a fast and reliable API with easy data storage and retrieval.

Getting started

To get started with FastAPI and PostgreSQL, you can follow these steps:

  1. Install FastAPI and the required dependencies:
$ pip install fastapi
$ pip install uvicorn[standard]
$ pip install databases[postgresql]
  1. Create a PostgreSQL database and user with appropriate permissions
  2. Initialize a FastAPI app and connect to the database:
from fastapi import FastAPI
from databases import Database

app = FastAPI()

DATABASE_URL = "postgresql://user:password@host:port/dbname"

database = Database(DATABASE_URL)

@app.on_event("startup")
async def startup():
    await database.connect()

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()
  1. Create a model for your data:
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
  1. Create a table in the database to store the data:
create_table_query = """
CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    name TEXT,
    description TEXT,
    price FLOAT,
    tax FLOAT
);
"""

async with database.transaction():
    await database.execute(create_table_query)
  1. Add CRUD (Create, Read, Update, Delete) endpoints to your app:
@app.post("/items/")
async def create_item(item: Item):
    query = """
    INSERT INTO items (name, description, price, tax)
    VALUES (:name, :description, :price, :tax)
    RETURNING id;
    """
    values = item.dict()
    return {"id": await database.execute(query=query, values=values)}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    query = """
    SELECT *
    FROM items
    WHERE id = :item_id;
    """
    return await database.fetch_one(query=query, values={"item_id": item_id})

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    query = """
    UPDATE items
    SET name = :name,
        description = :description,
        price = :price,
        tax = :tax
    WHERE id = :item_id;
    """
    values = item.dict()
    values.update({"item_id": item_id})
    return {"rows_updated": await database.execute(query=query, values=values)}

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    query = """
    DELETE FROM items
    WHERE id = :item_id;
    """
    return {"rows_deleted": await database.execute(query=query, values={"item_id": item_id})}
  1. Run the app with Uvicorn:
$ uvicorn main:app --reload
Conclusion

Combining FastAPI and PostgreSQL can give you a powerful, fast and reliable API with easy data storage and retrieval. It's a great choice for building APIs that need to handle large amounts of data and high concurrency.