I’m starting to work on a project with React and FastAPI.
On the server side:
from fastapi import APIRouter, Request, Depends, Response, encoders
import typing
import datetime
from app.db.session import get_db
from app.db.crud import (
create_lead,
)
from app.db.schemas import LeadCreate
leads_router = r = APIRouter()
@r.post("/leads", response_model=LeadCreate)
async def lead_create(
# request: Request,
lead: LeadCreate,
db=Depends(get_db),
):
lead.datetime_insert = datetime.datetime.now()
return create_lead(db, lead)
from pydantic import BaseModel
import datetime
class LeadCreate(BaseModel):
email: str
source: str
datetime_insert: datetime.datetime
class Config:
orm_mode = True
from sqlalchemy import Boolean, Column, Integer, String, DateTime
from .session import Base
class Lead(Base):
__tablename__ = "lead"
id = Column(Integer, primary_key=True, index=True)
email = Column(String)
source = Column(String)
datetime_insert = Column(DateTime)
In frontend side:
export const create_lead = async (email: string, source: string) => {
if (!(email.length > 0)) {
throw new Error('Email was not provided');
}
const d = {"email": email,
"source": source,
"datetime_insert": "",}
const request = new Request('/api/v1/leads', {
method: 'POST',
body: JSON.stringify(d),
});
const response = await fetch(request);
if (response.status === 500) {
throw new Error('Internal server error');
}
const data = await response.json();
if (response.status > 400 && response.status < 500) {
if (data.detail) {
throw data.detail;
}
throw data;
}
return data;
};
However, I’m getting the following error in the backend log:
"POST /api/v1/leads HTTP/1.0" 422 Unprocessable Entity
I have already tried to use FormData
. I think it is related to the data structure, where the frontend side is sending something different than the expected by server-side.