12

Good evening everyone. I'm trying to make a request to add new user to my database using FastAPI. When I try to do this through the python console app, FastAPI shows me this message:

{
     'detail': [
         {
             'loc': ['body', 'nickname'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'password'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'email'],
             'msg': 'field required',
             'type': 'value_error.missing'
         }
    ]
}

But when I do this request in /docs everything is working!

Here is my pydantic model:

class GetUserModel(BaseModel):
    nickname: str
    password: str
    email: str

    class Config:
        orm_mode = True

Here is my handler:

@users_router.post("/users/", status_code=200)
def add_new_user(user: GetUserModel, session: Session = Depends(get_session)):
    user.password = bcrypt.hashpw(
        user.password.encode(),
        bcrypt.gensalt()
    )  # password hashing

    new_user = User(**user.dict())
    add(session, new_user)  # adding to database

And here I'm trying to make a request:

response = requests.post(
                    'http://127.0.0.1:8000/users/',
                    data={
                        "nickname": "1",
                        "password": "1",
                        "email": "1"
                    })
print(response.json())

If you know what can be the problem, please tell me, I would really appreciate it!

Chris
  • 18,724
  • 6
  • 46
  • 80
Cross
  • 497
  • 1
  • 3
  • 13
  • 5
    try `request.post(url,json={your data dict})` i think it typically wants json data not normal form data (you can make it accept form data... but sending json is pretty easy) – Joran Beasley Jan 22 '22 at 18:05
  • 1
    Please have a look at [this answer](https://stackoverflow.com/a/70636163/17865804). – Chris Feb 16 '23 at 12:21

1 Answers1

1

As per the comments on your question, in order for your request to work, you need to perform the request with the json argument, as with data FastAPI assumes that you are sending Form Data:

response = requests.post(
    url='http://127.0.0.1:8000/users/',
    json={
        "nickname": "1",
        "password": "1",
        "email": "1"
    }
)

But, if you really want to send form data instead, you need to change your endpoint to accept Form params:

@users_router.post("/users/", status_code=200)
def add_new_user(
    nickname: str = Form(),
    password: str = Form(),
    email: str = Form(),
    session: Session = Depends(get_session)
):
    -- Endpoint handling here ---
John Moutafis
  • 22,254
  • 11
  • 68
  • 112