cygnus_server / api /examples.py
HPirela's picture
new changes
e9fe174
Raw History Blame Contribute Delete
2.53 kB
"""Endpoints for managing definition of examples.."""
from typing import List
from uuid import UUID
from fastapi import APIRouter, HTTPException
from db.models import Example
from database import get_mongo_client
from pydantic import BaseModel, Field
router = APIRouter(
prefix="/examples",
tags=["example definitions"],
responses={404: {"description": "Not found"}},
)
class CreateExample(BaseModel):
"""A request to create examples for a specific report type."""
examples: List[Example] = Field(..., description="A list of examples associated with the report type.")
class CreateExampleResponse(BaseModel):
"""Response for creating an example."""
result: int
@router.post("", response_model=CreateExampleResponse)
def create(
create_request: List[Example],
) -> CreateExampleResponse:
"""Endpoint to create an example."""
instance = [example.model_dump() for example in create_request]
db = get_mongo_client().Cygnus
example_collection=db["examples"]
result=example_collection.insert_many(instance)
return { "result":len(result.inserted_ids)}
@router.get("")
def list_examples(
report_type: str,
*,
limit: int = 10,
offset: int = 0,
) -> List[Example]:
"""Endpoint to get all examples."""
db = get_mongo_client().Cygnus
example_collection = db["examples"]
query = {"report_type": report_type}
examples_cursor = example_collection.find(query).skip(offset).limit(limit)
examples = [Example(**record) for record in examples_cursor]
return examples
# deleete all must be declared before delet uuid
@router.delete("/all")
def delete_all() -> int:
"""Endpoint to delete all examples."""
db = get_mongo_client().Cygnus
example_collection = db["examples"]
result = example_collection.delete_many({})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail="No examples found to delete.")
return result.deleted_count
@router.delete("/{uuid}")
def delete(
uuid: UUID
) -> None:
"""Endpoint to delete an example."""
db = get_mongo_client().Cygnus
example_collection = db["examples"]
example = example_collection.find_one({"uuid": uuid})
if example is None:
raise HTTPException(status_code=404, detail="Example not found.")
result = example_collection.delete_one({"uuid": uuid})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail="Example not found.")