Source Code: https://github.com/drtnn/facrud-router
Python 3.9+
facrud-router stands on the shoulders of giants:
$ pip install facrud-router
---> 100%
- Create a file
main.py
with:
import uuid
from dataclasses import dataclass
from dataclasses import field
import uvicorn
from facrud_router import ModelCRUDRouter
from fastapi import FastAPI
from pydantic import BaseModel, Field
from sqlalchemy import Column, String
from sqlalchemy.dialects.postgresql import UUID
from app.api.deps import get_session
from app.api.deps import authentication_scheme
app = FastAPI(
title="FastAPI CURD Router Demo",
version="0.1.2",
description="FastAPI CRUD Router for SQLAlchemy",
openapi_url="/openapi.json",
docs_url="/",
)
@dataclass
class User:
__sa_dataclass_metadata_key__ = "sa"
__tablename__ = "user"
id: uuid.UUID = field(
init=False,
default_factory=uuid.uuid4,
metadata={"sa": Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)},
)
username: str = field(metadata={"sa": Column(String(255), nullable=False, index=True)})
full_name: str = field(metadata={"sa": Column(String(255), nullable=False)})
class UserRequestSchema(BaseModel):
username: str = Field(title="Username", max_length=255)
full_name: str = Field(title="User Full Name", max_length=255)
class UserResponseSchema(BaseModel):
id: uuid.UUID = Field(title="User Id")
username: str = Field(title="Username", max_length=255)
full_name: str = Field(title="User Full Name", max_length=255)
router = ModelCRUDRouter(
prefix="user",
model=User,
identifier_type=uuid.UUID,
get_session=get_session,
get_authentication=authentication_scheme,
request_schema=UserRequestSchema,
response_schema=UserResponseSchema
)
app.include_router(router.api_router)
if __name__ == "__main__":
uvicorn.run(app)
Run the server with:
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
You already created an API that:
- GET
/user/{user_id}
retrieves User object by UUID. - GET
/user
returns list of User objects. - POST
/user
creates User object. - DELETE
/user/{user_id}
deletes User object by UUID. - PUT
/user/{user_id}
updates User object by UUID. - PATCH
/user/{user_id}
partial updates User object by UUID.
Now go to http://127.0.0.1:8000.
You will see the automatic interactive API documentation (provided by Swagger UI):
This project is licensed under the terms of the Apache License 2.0.