43 lines
2.2 KiB
Python
43 lines
2.2 KiB
Python
Here's the `and.py` file for the `app/api/v1/routes/` directory with the specified endpoints:
|
|
|
|
```python
|
|
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1.models.and import And
|
|
from app.api.v1.schemas.and import AndCreate, AndResponse
|
|
from app.api.core.dependencies.dependencies import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/ands", response_model=List[AndResponse])
|
|
def read_ands(db: Session = Depends(get_db)):
|
|
ands = db.query(And).all()
|
|
return ands
|
|
|
|
@router.post("/ands", response_model=AndResponse)
|
|
def create_and(and_data: AndCreate, db: Session = Depends(get_db)):
|
|
and_db = And(**and_data.dict())
|
|
db.add(and_db)
|
|
db.commit()
|
|
db.refresh(and_db)
|
|
return and_db
|
|
|
|
@router.get("/ands/{id}", response_model=AndResponse)
|
|
def read_and(id: int, db: Session = Depends(get_db)):
|
|
and_db = db.query(And).get(id)
|
|
if not and_db:
|
|
raise HTTPException(status_code=404, detail="And not found")
|
|
return and_db
|
|
```
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules and classes from FastAPI, SQLAlchemy, and the project's models and schemas.
|
|
2. We create an instance of `APIRouter` to define our routes.
|
|
3. The `read_ands` function handles the `GET /ands` endpoint. It uses the `get_db` dependency to obtain a database session, queries all `And` objects from the database, and returns them as a list of `AndResponse` objects.
|
|
4. The `create_and` function handles the `POST /ands` endpoint. It takes an `AndCreate` object as input, creates a new `And` object from the data, adds it to the database session, commits the changes, and returns the newly created `And` object as an `AndResponse`.
|
|
5. The `read_and` function handles the `GET /ands/{id}` endpoint. It takes an `id` parameter, queries the database for an `And` object with the given ID, and returns it as an `AndResponse`. If no `And` object is found, it raises an `HTTPException` with a 404 status code.
|
|
|
|
Note: This code assumes that you have defined the `And` model in `app.api.v1.models.and` and the `AndCreate` and `AndResponse` schemas in `app.api.v1.schemas.and`. Additionally, the `get_db` dependency function should be defined in `app.api.core.dependencies.dependencies`. |