Simple Read Endpoint#

Create a basic GET endpoint that queries the database.

Goal#

Build GET /instruments/{id} endpoint that returns instrument details.

Step 1: Create Router File#

Create ccat_ops_db_api/routers/my_router.py:

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ccat_ops_db import models
from ..dependencies import get_db
from ..schemas import InstrumentResponse

router = APIRouter(prefix="/my-endpoint", tags=["my-endpoint"])

@router.get("/{instrument_id}", response_model=InstrumentResponse)
async def get_instrument(
    instrument_id: int,
    db: Session = Depends(get_db)
):
    """Get instrument by ID"""
    instrument = db.query(models.Instrument).filter(
        models.Instrument.id == instrument_id
    ).first()

    if not instrument:
        raise HTTPException(status_code=404, detail="Instrument not found")

    return instrument

Step 2: Define Schema#

In schemas.py:

from pydantic import BaseModel

class InstrumentResponse(BaseModel):
    id: int
    name: str
    description: str
    is_active: bool

    class Config:
        from_attributes = True

Step 3: Register Router#

In main.py:

from .routers import my_router

app.include_router(my_router.router)

Step 4: Test#

curl http://localhost:8000/my-endpoint/1

Expected response:

{
  "id": 1,
  "name": "CCAT-prime",
  "description": "Prime-Cam instrument",
  "is_active": true
}

Next: Simple Write Endpoint