Update code in endpoints/states.post.py

This commit is contained in:
Backend IM Bot 2025-03-25 15:47:48 +01:00
parent d3124ea47a
commit 7843150ffe

62
endpoints/states.post.py Normal file
View File

@ -0,0 +1,62 @@
Sure, here's an example of a FastAPI endpoint that creates a new state in the database using SQLAlchemy models and Pydantic schemas:
```python
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models import State
from schemas import StateCreate, StateResponse
router = APIRouter(
prefix="/states",
tags=["States"],
)
@router.post("/", response_model=StateResponse)
def create_state(state: StateCreate, db: Session = Depends(get_db)):
db_state = State(**state.dict())
db.add(db_state)
db.commit()
db.refresh(db_state)
return db_state
# models.py
from sqlalchemy import Column, Integer, String
from database import Base
from app.api.models.states_model import *
from app.api.schemas.states_schema import *
class StateCreate(StateBase):
pass
class StateResponse(StateBase):
id: int
class Config:
orm_mode = True
```
In this example, we have the following components:
1. `models.py`: This file defines the SQLAlchemy model `State` with columns for `id`, `name`, and `abbreviation`.
2. `schemas.py`: This file defines the Pydantic schemas for creating and responding with state data. `StateBase` is a base class with common attributes, `StateCreate` inherits from `StateBase` and is used for creating new states, and `StateResponse` inherits from `StateBase` and includes the `id` field for responding with the created state.
3. `router.py`: This file defines the FastAPI router and the `create_state` endpoint. The `create_state` function takes a `StateCreate` object as input, creates a new `State` instance from the input data, adds it to the database session, commits the changes, and returns the created `State` instance as a `StateResponse` object.
To use this endpoint, you would send a POST request to `/states/` with a JSON payload containing the `name` and `abbreviation` fields. For example:
```
POST /states/
Content-Type: application/json
{
"name": "California",
"abbreviation": "CA"
}
```
The endpoint will create a new state in the database and return the created state with its `id` in the response.
Note that you'll need to set up the database connection and session management using SQLAlchemy, which is not shown in this example. You'll also need to create the database tables by running the appropriate SQLAlchemy commands or using an ORM migration tool like Alembic.