axios post request error with 422 (Unprocessable Entity) from react

Viewed 2696

from FastAPI & sqlalchemy

@app.post("/users")
    def create_users(email: str, pwd: str, first_name: str, last_name: str, phone_number: str, city: str):
        user = UserTable()
        user.email = email
        user.pwd = pwd
        user.first_name = first_name
        user.last_name = last_name
        user.phone_number = phone_number
        user.city = city
    

        session.add(user)
        session.commit()
    
        return f"{email} created..."

React axios.post request

const addUserHandler =  () => {
        console.log(email, pwd, first_name, last_name, phone_number, city);
        axios
            .post('http://localhost:8000/users', {
                email: email,
                pwd: pwd,
                first_name: first_name,
                last_name: last_name,
                phone_number: phone_number,
                city: city,
            })
            .then((res) => console.log(res.data))
            .catch((error) => {
                console.log(error.response.data);
            });
        console.log(city);
    };

below is error code

xhr.js:177 POST http://localhost:8000/users 422 (Unprocessable Entity)
App.js:37 
{detail: Array(6)}
detail: Array(6)
0: {loc: Array(2), msg: "field required", type: "value_error.missing"}
1: {loc: Array(2), msg: "field required", type: "value_error.missing"}
2: {loc: Array(2), msg: "field required", type: "value_error.missing"}
3: {loc: Array(2), msg: "field required", type: "value_error.missing"}
4: {loc: Array(2), msg: "field required", type: "value_error.missing"}
5: {loc: Array(2), msg: "field required", type: "value_error.missing"}
length: 6
__proto__: Array(0)
__proto__: Object

code is from react & axios and i got 422 error and couldnt post. i did check variables(useState) had a each string. but error still shows "field required" and "value_error.missing". how can i fix ths?

thaks for any reply!

1 Answers

The problem is that you are expecting "query params" in the url (fastapi), not a json body.

So,

@app.post("/users")
    def create_users(email: str, pwd: str, first_name: str, last_name: str, phone_number: str, city: str):

is expecting something like

/users?email=a&pwd=b&first_name=c...

Try working with Pydantic models, that way fastapi will be waiting a body in the request.

Related