Certainly! Below is an implementation using FastAPI and SQLModel that accepts a POST request to create a coupon with the structure you've provided. This implementation includes:
Models using SQLModel
An API endpoint to accept the POST request
Database interaction with SQLite using SQLModel
Let's go through the steps.
Step 1: Install Dependencies
First, ensure you have the necessary libraries installed:
bash
pip install fastapi uvicorn sqlmodel
Step 2: Define the Models
We'll define two models:
RepeatCountsInput: A Pydantic model (inherits from SQLModel without table information) to validate the nested repeat_counts data coming in the request.
CouponInput: A Pydantic model for the incoming coupon data.
Coupon: The SQLModel model that represents the database table.
python
from typing import Optional
from sqlmodel import SQLModel, Field
class RepeatCountsInput(SQLModel):
user_total: int
user_daily: int
user_weekly: int
global_total: int
class CouponInput(SQLModel):
code: str
repeat_counts: RepeatCountsInput
class Coupon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True) # Auto-incrementing ID
code: str
user_total: int
user_daily: int
user_weekly: int
global_total: int
Replace "your_script_name:app" with the name of your Python script file.
Full Code Example
python
from typing import Optional
from fastapi import FastAPI, HTTPException
from sqlmodel import SQLModel, Field, Session, create_engine
# Define the models
class RepeatCountsInput(SQLModel):
user_total: int
user_daily: int
user_weekly: int
global_total: int
class CouponInput(SQLModel):
code: str
repeat_counts: RepeatCountsInput
class Coupon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
code: str
user_total: int
user_daily: int
user_weekly: int
global_total: int
# Set up the database engine
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
# Create the database tables
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
# Initialize FastAPI
app = FastAPI()
# API endpoint to create a coupon
@app.post("/api/coupons", response_model=Coupon)
def create_coupon(coupon_in: CouponInput):
coupon = Coupon(
code=coupon_in.code,
user_total=coupon_in.repeat_counts.user_total,
user_daily=coupon_in.repeat_counts.user_daily,
user_weekly=coupon_in.repeat_counts.user_weekly,
global_total=coupon_in.repeat_counts.global_total
)
with Session(engine) as session:
session.add(coupon)
session.commit()
session.refresh(coupon)
return coupon
# Main entry point
if __name__ == "__main__":
import uvicorn
create_db_and_tables()
uvicorn.run("your_script_name:app", host="127.0.0.1", port=8000, reload=True)
Testing the Endpoint
You can test the endpoint using the provided curl command: