|
1 | 1 | # FastAPI-REST-JSONAPI
|
2 | 2 |
|
3 |
| -## Examples: |
| 3 | +FastAPI-REST-JSONAPI is a FastAPI extension for building REST APIs. |
| 4 | +Implementation of a strong specification [JSONAPI 1.0](http://jsonapi.org/). |
| 5 | +This framework is designed to quickly build REST APIs and fit the complexity |
| 6 | +of real life projects with legacy data and multiple data storages. |
4 | 7 |
|
5 |
| -### 1. App API-FOR-TORTOISE-ORM |
6 | 8 |
|
7 |
| - |
8 |
| -#### Install dependencies |
9 |
| -```shell |
10 |
| -pip install -r requirements.txt |
11 |
| -pip install -r requirements-dev.txt |
| 9 | +## Install |
| 10 | +```bash |
| 11 | +pip install FastAPI-REST-JSONAPI |
12 | 12 | ```
|
13 | 13 |
|
| 14 | +## A minimal API |
| 15 | + |
| 16 | +Create a test.py file and copy the following code into it |
| 17 | + |
| 18 | +```python |
| 19 | +import sys |
| 20 | +from pathlib import Path |
| 21 | +from typing import Any, Dict, List, Union, Optional |
| 22 | + |
| 23 | +import uvicorn |
| 24 | +from fastapi import APIRouter, Depends, FastAPI |
| 25 | +from pydantic import BaseModel |
| 26 | +from sqlalchemy import Column, Text, Integer, select |
| 27 | +from sqlalchemy.engine import make_url |
| 28 | +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine |
| 29 | +from sqlalchemy.ext.declarative import declarative_base |
| 30 | +from sqlalchemy.orm import sessionmaker |
| 31 | +from sqlalchemy.sql import Select |
| 32 | + |
| 33 | +from fastapi_rest_jsonapi import RoutersJSONAPI |
| 34 | +from fastapi_rest_jsonapi import SqlalchemyEngine |
| 35 | +from fastapi_rest_jsonapi.data_layers.orm import DBORMType |
| 36 | +from fastapi_rest_jsonapi.openapi import custom_openapi |
| 37 | +from fastapi_rest_jsonapi.querystring import QueryStringManager |
| 38 | +from fastapi_rest_jsonapi.schema import JSONAPIResultListSchema |
| 39 | +from fastapi_rest_jsonapi.schema import collect_app_orm_schemas |
| 40 | + |
| 41 | +CURRENT_FILE = Path(__file__).resolve() |
| 42 | +CURRENT_DIR = CURRENT_FILE.parent |
| 43 | +PROJECT_DIR = CURRENT_DIR.parent.parent |
| 44 | + |
| 45 | +sys.path.append(str(PROJECT_DIR)) |
| 46 | + |
| 47 | +Base = declarative_base() |
| 48 | + |
| 49 | + |
| 50 | +def async_session() -> sessionmaker: |
| 51 | + uri = "sqlite+aiosqlite:///db.sqlite3" |
| 52 | + engine = create_async_engine(url=make_url(uri)) |
| 53 | + _async_session = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False) |
| 54 | + return _async_session |
| 55 | + |
| 56 | + |
| 57 | +class Connector: |
| 58 | + |
| 59 | + @classmethod |
| 60 | + async def get_session(cls): |
| 61 | + """ |
| 62 | + Getting a session to the database. |
| 63 | +
|
| 64 | + :return: |
| 65 | + """ |
| 66 | + async_session_ = async_session() |
| 67 | + async with async_session_() as db_session: |
| 68 | + async with db_session.begin(): |
| 69 | + yield db_session |
| 70 | + |
| 71 | + |
| 72 | +class User(Base): |
| 73 | + __tablename__ = "users" |
| 74 | + id = Column(Integer, primary_key=True, autoincrement=True) |
| 75 | + first_name: str = Column(Text, nullable=True) |
| 76 | + |
| 77 | + |
| 78 | +class UserBaseSchema(BaseModel): |
| 79 | + """User base schema.""" |
| 80 | + |
| 81 | + class Config: |
| 82 | + """Pydantic schema config.""" |
| 83 | + orm_mode = True |
| 84 | + |
| 85 | + first_name: Optional[str] = None |
| 86 | + |
| 87 | + |
| 88 | +class UserPatchSchema(UserBaseSchema): |
| 89 | + """User PATCH schema.""" |
| 90 | + |
| 91 | + |
| 92 | +class UserInSchema(UserBaseSchema): |
| 93 | + """User input schema.""" |
| 94 | + |
| 95 | + |
| 96 | +class UserSchema(UserInSchema): |
| 97 | + """User item schema.""" |
| 98 | + |
| 99 | + class Config: |
| 100 | + """Pydantic model config.""" |
| 101 | + orm_mode = True |
| 102 | + model = "users" |
| 103 | + |
| 104 | + id: int |
| 105 | + |
| 106 | + |
| 107 | +class UserDetail: |
| 108 | + |
| 109 | + @classmethod |
| 110 | + async def get(cls, obj_id: int, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 111 | + user: User = (await session.execute(select(User).where(User.id == obj_id))).scalar_one() |
| 112 | + return UserSchema.from_orm(user) |
| 113 | + |
| 114 | + @classmethod |
| 115 | + async def patch(cls, obj_id: int, data: UserPatchSchema, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 116 | + user: User = (await session.execute(select(User).where(User.id == obj_id))).scalar_one() |
| 117 | + user.first_name = data.first_name |
| 118 | + await session.commit() |
| 119 | + return UserSchema.from_orm(user) |
| 120 | + |
| 121 | + @classmethod |
| 122 | + async def delete(cls, obj_id: int, session: AsyncSession = Depends(Connector.get_session)) -> None: |
| 123 | + user: User = (await session.execute(select(User).where(User.id == obj_id))).scalar_one() |
| 124 | + await session.delete(user) |
| 125 | + await session.commit() |
| 126 | + |
| 127 | + |
| 128 | +class UserList: |
| 129 | + @classmethod |
| 130 | + async def get( |
| 131 | + cls, query_params: QueryStringManager, session: AsyncSession = Depends(Connector.get_session) |
| 132 | + ) -> Union[Select, JSONAPIResultListSchema]: |
| 133 | + user_query = select(User) |
| 134 | + dl = SqlalchemyEngine(query=user_query, schema=UserSchema, model=User, session=session) |
| 135 | + count, users_db = await dl.get_collection(qs=query_params) |
| 136 | + total_pages = count // query_params.pagination.size + (count % query_params.pagination.size and 1) |
| 137 | + users: List[UserSchema] = [UserSchema.from_orm(i_user) for i_user in users_db] |
| 138 | + return JSONAPIResultListSchema( |
| 139 | + meta={"count": count, "totalPages": total_pages}, |
| 140 | + data=[{"id": i_obj.id, "attributes": i_obj.dict(), "type": "user"} for i_obj in users], |
| 141 | + ) |
| 142 | + |
| 143 | + @classmethod |
| 144 | + async def post(cls, data: UserInSchema, session: AsyncSession = Depends(Connector.get_session)) -> UserSchema: |
| 145 | + user = User(first_name=data.first_name) |
| 146 | + session.add(user) |
| 147 | + await session.commit() |
| 148 | + return UserSchema.from_orm(user) |
| 149 | + |
| 150 | + |
| 151 | +def add_routes(app: FastAPI) -> List[Dict[str, Any]]: |
| 152 | + tags = [ |
| 153 | + { |
| 154 | + "name": "User", |
| 155 | + "description": "", |
| 156 | + }, |
| 157 | + ] |
| 158 | + |
| 159 | + routers: APIRouter = APIRouter() |
| 160 | + RoutersJSONAPI( |
| 161 | + routers=routers, |
| 162 | + path="/user", |
| 163 | + tags=["User"], |
| 164 | + class_detail=UserDetail, |
| 165 | + class_list=UserList, |
| 166 | + schema=UserSchema, |
| 167 | + type_resource="user", |
| 168 | + schema_in_patch=UserPatchSchema, |
| 169 | + schema_in_post=UserInSchema, |
| 170 | + model=User, |
| 171 | + engine=DBORMType.sqlalchemy, |
| 172 | + ) |
| 173 | + |
| 174 | + app.include_router(routers, prefix="") |
| 175 | + return tags |
| 176 | + |
| 177 | + |
| 178 | +async def sqlalchemy_init() -> None: |
| 179 | + uri = "sqlite+aiosqlite:///db.sqlite3" |
| 180 | + engine = create_async_engine(url=make_url(uri)) |
| 181 | + async with engine.begin() as conn: |
| 182 | + await conn.run_sync(Base.metadata.drop_all) |
| 183 | + await conn.run_sync(Base.metadata.create_all) |
| 184 | + |
| 185 | + |
| 186 | +def create_app() -> FastAPI: |
| 187 | + """ |
| 188 | + Create app factory. |
| 189 | +
|
| 190 | + :return: app |
| 191 | + """ |
| 192 | + app = FastAPI( |
| 193 | + title="FastAPI and SQLAlchemy", |
| 194 | + debug=True, |
| 195 | + openapi_url="/openapi.json", |
| 196 | + docs_url="/docs", |
| 197 | + ) |
| 198 | + add_routes(app) |
| 199 | + app.on_event("startup")(sqlalchemy_init) |
| 200 | + custom_openapi(app, title="API for SQLAlchemy") |
| 201 | + collect_app_orm_schemas(app) |
| 202 | + return app |
| 203 | + |
| 204 | + |
| 205 | +app = create_app() |
| 206 | + |
14 | 207 |
|
15 |
| -#### Start app |
16 |
| -```shell |
17 |
| -# in dir fastapi-rest-jsonapi |
| 208 | +if __name__ == "__main__": |
| 209 | + uvicorn.run( |
| 210 | + "test:app", |
| 211 | + host="0.0.0.0", |
| 212 | + port=8084, |
| 213 | + reload=True, |
| 214 | + app_dir=str(CURRENT_DIR), |
| 215 | + ) |
18 | 216 |
|
19 |
| -export PYTHOPATH="${PYTHONPATH}:./" |
20 |
| -# reload may not work :( |
21 |
| -python examples/api_for_tortoise_orm/main.py |
22 | 217 | ```
|
23 | 218 |
|
24 |
| -Visit http://0.0.0.0:8080/docs |
| 219 | +This example provides the following API structure: |
25 | 220 |
|
| 221 | +| URL | method | endpoint | Usage | |
| 222 | +|-------------------|--------|---------------|---------------------------| |
| 223 | +| /user | GET | user_list | Get a collection of users | |
| 224 | +| /user | POST | user_list | Create a user | |
| 225 | +| /user/< int:int > | GET | user_detail | Get user details | |
| 226 | +| /user/< int:int > | PATCH | person_detail | Update a user | |
| 227 | +| /user/< int:int > | DELETE | person_detail | Delete a user | |
0 commit comments