Update code in endpoints/manner.get.py
This commit is contained in:
parent
7fb1530ee1
commit
a1423bd442
50
endpoints/manner.get.py
Normal file
50
endpoints/manner.get.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
Here's an example of a FastAPI endpoint that returns a list of books from the database:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# models/book.py
|
||||||
|
from sqlalchemy import Column, Integer, String
|
||||||
|
from core.database import Base
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
||||||
|
|
||||||
|
# endpoints/books.py
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from core.database import get_db
|
||||||
|
from models.book import Book
|
||||||
|
from schemas.book import BookSchema
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.get("/books", response_model=List[BookSchema])
|
||||||
|
|
||||||
|
Here's a breakdown of the code:
|
||||||
|
|
||||||
|
1. `models/book.py`: Defines the SQLAlchemy model `Book` with columns for `id`, `title`, `author`, and `description`.
|
||||||
|
2. `schemas/book.py`: Defines the Pydantic schema `BookSchema` for data validation and serialization/deserialization.
|
||||||
|
3. `endpoints/books.py`:
|
||||||
|
- Imports necessary dependencies and models.
|
||||||
|
- Defines a `router` instance.
|
||||||
|
- The `get_books` function is decorated with `@router.get("/books", response_model=List[BookSchema])`, which specifies the endpoint path and the response model.
|
||||||
|
- Inside the `get_books` function, it retrieves all books from the database using `db.query(Book).all()`.
|
||||||
|
- The retrieved books are returned as the response.
|
||||||
|
|
||||||
|
To use this endpoint, you would need to include the `router` in your main FastAPI application:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# main.py
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from endpoints.books import router as book_router
|
||||||
|
|
||||||
|
from app.api.models.manner_model import *
|
||||||
|
from app.api.schemas.manner_schema import *
|
||||||
|
from app.api.dependencies.manner_deps import *
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(book_router)
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, you can access the endpoint at `/books` using a GET request. The response will be a JSON array containing the list of books from the database.
|
||||||
|
|
||||||
|
Note: Make sure to replace the import paths (`core.database`, `models.book`, `schemas.book`) with the correct paths based on your project structure.
|
Loading…
x
Reference in New Issue
Block a user