81 lines
2.6 KiB
Python
81 lines
2.6 KiB
Python
Sure, here's an example of a FastAPI endpoint that saves data to a database using SQLAlchemy and Pydantic:
|
|
|
|
```python
|
|
from fastapi import FastAPI, HTTPException
|
|
from pydantic import BaseModel
|
|
from sqlalchemy import Column, Integer, String
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
app = FastAPI()
|
|
|
|
# SQLAlchemy setup
|
|
Base = declarative_base()
|
|
engine = create_engine('sqlite:///database.db', connect_args={'check_same_thread': False})
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Pydantic model (schema)
|
|
class PenSchema(BaseModel):
|
|
name: str
|
|
color: str
|
|
price: float
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
|
|
# SQLAlchemy model
|
|
class Pen(Base):
|
|
__tablename__ = 'pens'
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
name = Column(String)
|
|
color = Column(String)
|
|
price = Column(Integer)
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
# Dependency
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
@app.post('/pen', status_code=201)
|
|
def create_pen(pen: PenSchema, db=get_db()):
|
|
new_pen = Pen(name=pen.name, color=pen.color, price=pen.price)
|
|
db.add(new_pen)
|
|
db.commit()
|
|
db.refresh(new_pen)
|
|
return new_pen
|
|
```
|
|
|
|
Here's a breakdown of the code:
|
|
|
|
1. We import the necessary modules and create a FastAPI instance.
|
|
2. We set up SQLAlchemy with a SQLite database and define a base class for our models.
|
|
3. We define a Pydantic model (`PenSchema`) to validate and parse the incoming data.
|
|
4. We define a SQLAlchemy model (`Pen`) that maps to the `pens` table in the database.
|
|
5. We create the `pens` table in the database using `Base.metadata.create_all(bind=engine)`.
|
|
6. We define a dependency function `get_db()` that creates a new database session for each request and closes it after the request is processed.
|
|
7. We define the `/pen` endpoint with the `POST` method and the `status_code=201` (Created) response.
|
|
8. Inside the endpoint function, we create a new `Pen` instance using the data from the `PenSchema` model.
|
|
9. We add the new `Pen` instance to the database session, commit the changes, and refresh the instance to get the generated ID.
|
|
10. Finally, we return the new `Pen` instance.
|
|
|
|
To use this endpoint, you can send a POST request to `/pen` with a JSON payload containing the pen details, like this:
|
|
|
|
```
|
|
POST /pen
|
|
Content-Type: application/json
|
|
|
|
{
|
|
"name": "Pilot FriXion",
|
|
"color": "Black",
|
|
"price": 2.99
|
|
}
|
|
```
|
|
|
|
The endpoint will create a new pen in the database and return the created pen object with the generated ID. |