ohmyapi/docs/routes.md
Brian Wiborg 91baf968d7
📝 Add mkdocs
2025-10-02 01:01:57 +02:00

2.1 KiB

Routes

OhMyAPI uses FastAPI - a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.

Routes are exposed via a module named routes in the app's directory. OhMyAPI auto-detects all fastapi.APIRouter instances exposed this way. If the routes module is a package, OhMyAPI will search through its submodules recursively.

When creating an app via startapp, OhMyAPI will provide CRUD boilerplate to help your get started.

Example CRUD API endpoints

from ohmyapi.db.exceptions import DoesNotExist

from ohmyapi.router import APIRouter, HTTPException, HTTPStatus

from .models import Restaurant

from typing import List

router = APIRouter(prefix="/restaurant", tags=['restaurant'])


@router.get("/", response_model=List[Restaurant])
async def list():
    """List all restaurants."""
    queryset = Restaurant.all()
    schema = Restaurant.Schema()
    return await schema.from_queryset(queryset)
    # or in one line:
    # return await Restaurant.Schema().from_queryset(Restaurant.all())


@router.post("/", status_code=HTTPStatus.CREATED)
async def post(restaurant: Restaurant.Schema(readonly=True)):
    """Create a new restaurant."""
    return await Restaurant(**restaurant.model_dump()).create()


@router.get("/{id}", response_model=Restaurant)
async def get(id: str):
    """Get restaurant by ID."""
    return await Restaurant.Schema().from_queryset(Restaurant.get(id=id))


@router.put("/{id}", status_code=HTTPStatus.ACCEPTED)
async def put(restaurant: Restaurant):
    """Update restaurant."""
    try:
        db_restaurant = await Restaurant.get(id=id)
    except DoesNotExist:
        return HTTPException(status_code=HTTPStatus.NOT_FOUND)

    db_restaurant.update_from_dict(restaurant.model_dump())
    return await db_restaurant.save()


@router.delete("/{id}", status_code=HTTPStatus.ACCEPTED)
async def delete(id: str):
    try:
        db_restaurant = await Restaurant.get(id=id)
    except DoesNotExist:
        return HTTPException(status_code=HTTPStatus.NOT_FOUND)

    return await db_restaurant.delete()