feat(api): Initial API server and stamps routes.

This commit is contained in:
2025-06-07 05:29:00 +10:00
parent a02cc0977a
commit 77dc90cc32
5 changed files with 652 additions and 0 deletions

87
src/api.py Normal file
View File

@@ -0,0 +1,87 @@
import sys
import os
import asyncio
from aiohttp import web
import logging
from meta import conf
from data import Database
from utils.auth import key_auth_factory
from datamodels import DataModel
from constants import DATA_VERSION
from routes.stamps import routes as stamp_routes
from routes.lib import dbvar, datamodelsv
sys.path.insert(0, os.path.join(os.getcwd()))
sys.path.insert(0, os.path.join(os.getcwd(), "src"))
logger = logging.getLogger(__name__)
"""
- `/stamps` with `POST`, `PUT`, `GET`
- `/stamps/{stamp_id}` with `GET`, `PATCH`, `DELETE`
- `/documents` with `POST, GET`
- `/documents/{document_id}` with `GET`, `PATCH`, `DELETE`
- `/documents/{document_id}/stamps` which is passed to `/stamps` with `document_id` set.
- `/events` with `POST`, `GET`
- `/events/{event_id}` with `GET`, `PATCH`, `DELETE`
- `/events/{event_id}/document` which is passed to `/documents/{document_id}`
- `/events/{event_id}/user` which is passed to `/users/{user_id}`
- `/users` with `POST`, `GET`, `PATCH`, `DELETE`
- `/users/{user_id}` with `GET`, `PATCH`, `DELETE`
- `/users/{user_id}/events` which is passed to `/events`
- `/users/{user_id}/specimen` which is passed to `/specimens/{specimen_id}`
- `/users/{user_id}/specimens` which is passed to `/specimens`
- `/users/{user_id}/wallet` with `GET`
- `/users/{user_id}/transactions` which is passed to `/transactions`
- `/specimens` with `GET` and `POST`
- `/specimens/{specimen_id}` with `PATCH` and `DELETE`
- `/specimens/{specimen_id}/owner` which is passed to `/users/{user_id}`
- `/transactions` with `POST`, `GET`
- `/transactions/{transaction_id}` with `GET`, `PATCH`, `DELETE`
- `/transactions/{transaction_id}/user` which is passed to `/users/{user_id}`
"""
async def attach_db(app: web.Application):
db = Database(conf.data['args'])
async with db.open():
version = await db.version()
if version.version != DATA_VERSION:
error = f"Data model version is {version}, required version is {DATA_VERSION}! Please migrate."
logger.critical(error)
raise RuntimeError(error)
datamodel = DataModel()
db.load_registry(datamodel)
await datamodel.init()
app[dbvar] = db
app[datamodelsv] = datamodel
yield
async def test(request: web.Request) -> web.Response:
return web.Response(text="Hello World")
async def app_factory():
auth = key_auth_factory(conf.API['TOKEN'])
app = web.Application(middlewares=[auth])
app.cleanup_ctx.append(attach_db)
app.router.add_get('/', test)
app.router.add_routes(stamp_routes)
return app
async def run_app():
app = await app_factory()
web.run_app(app)
if __name__ == '__main__':
asyncio.run(run_app())