title: ReactJS Signup Form Submission FastAPI 422 Unprocessable Entity
body: <p>From FastAPI and Sqlalchemy.</p>
  <pre><code>@router.post(&quot;/signup&quot;, response_model=ShowUser)
  async def create_user(form_data: UserCreate = Depends(), users: Users = Depends(get_user_db)):
      # CHECK IF USER ALREADY EXISTS
      if await users.get_user_by_email(email=form_data.email) is not None:
          raise HTTPException(
              status_code=status.HTTP_400_BAD_REQUEST,
              detail=&quot;User already exists&quot;
          )
      # CHECK IF USERNAME ALREADY EXISTS
      elif await users.get_user_by_username(username=form_data.username) is not None:
          raise HTTPException(
              status_code=status.HTTP_400_BAD_REQUEST,
              detail=&quot;Username already exists&quot;
          )
  
      # CREATE USER WITH USERS METHOD
      # now the hashing of the password is done directly in the creation method
      new_user = await users.create_user(form_data)
      
      # GET TOKEN
      # we no longer create a new uid for JTI, but use the one created automatically during user creation
      # so I modified the get_confirmation_token function so that it takes the user's JTI uid as a parameter
      confirmation_token = Auth.get_confirmation_token(
                              new_user.email,
                              new_user.confirmation)
  
      # SEND AN EMAIL WITH TOKEN
      try:
          Mailer.send_confirmation_message(
              confirmation_token[&quot;token&quot;], form_data.email)
      except ConnectionRefusedError:
          raise HTTPException(
              status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
              detail=&quot;Email couldn't be send. Please try again.&quot;
          )
      # RETURN USER
      return new_user
  </code></pre>
  <p>Pydantic MOdels.</p>
  <pre><code>from typing import Optional
  from pydantic import BaseModel, EmailStr
  from fastapi import Form
  
  def form_body(cls):
      cls.__signature__ = cls.__signature__.replace(
          parameters=[
              arg.replace(default=Form(...))
              for arg in cls.__signature__.parameters.values()
          ]
      )
      return cls
  
  @form_body
  class UserCreate(BaseModel):
      username: str
      email: EmailStr
      password: str
  
      class Config():
          orm_mode = True
  
  class ShowUser(BaseModel):
      username: str
      email: EmailStr
      is_active: bool
  
      class Config():
          orm_mode = True
  </code></pre>
  <p>React Signup Form Submission.</p>
  <pre><code>import React, { useContext, useState } from &quot;react&quot;;
  import axios from 'axios';
  import Cookies from 'js-cookie';
  
  import { UserContext } from &quot;../context/UserContext&quot;;
  import ErrorMessage from &quot;./ErrorMessage&quot;;
  
  const Register = () =&gt; {
    const [username, setUserName] = useState(&quot;&quot;);
    const [email, setEmail] = useState(&quot;&quot;);
    const [password, setPassword] = useState(&quot;&quot;);
    const [errorMessage, setErrorMessage] = useState(&quot;&quot;);
    const [, setToken] = useContext(UserContext);
  
    
    const submitRegistration = async () =&gt; {
      const requestOptions = {
        method: &quot;POST&quot;,
        headers: { &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot; },
        body: JSON.stringify({ username: username, email: email, password: password }),
      };
  
      await axios
          .post(&quot;/api/signup&quot;, requestOptions)
          .then((response) =&gt; {
            console.log(response);
            alert(response);
            Cookies.set(&quot;token&quot;, response.data.access_token);
            return response;
          })
          .catch((error) =&gt; {
            console.log(error.message);
            alert(error);
          });
    };
  
    const handleSubmit = (e) =&gt; {
      e.preventDefault();
      if (username.length &gt; 5) {
        submitRegistration();
      } else {
        setErrorMessage(
          &quot;Ensure that the passwords match and greater than 5 characters&quot;
        );
      }
    };
  
    return (
      &lt;div className=&quot;column&quot;&gt;
        &lt;form className=&quot;box&quot; onSubmit={handleSubmit}&gt;
          &lt;h1 className=&quot;title has-text-centered&quot;&gt;Register&lt;/h1&gt;
          &lt;div className=&quot;field&quot;&gt;
            &lt;label className=&quot;label&quot;&gt;Username&lt;/label&gt;
            &lt;div className=&quot;control&quot;&gt;
              &lt;input
                type=&quot;username&quot;
                placeholder=&quot;Enter username&quot;
                value={username}
                onChange={(e) =&gt; setUserName(e.target.value)}
                className=&quot;input&quot;
                required
              /&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div className=&quot;field&quot;&gt;
            &lt;label className=&quot;label&quot;&gt;Email&lt;/label&gt;
            &lt;div className=&quot;control&quot;&gt;
              &lt;input
                type=&quot;email&quot;
                placeholder=&quot;Enter email&quot;
                value={email}
                onChange={(e) =&gt; setEmail(e.target.value)}
                className=&quot;input&quot;
                required
              /&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div className=&quot;field&quot;&gt;
            &lt;label className=&quot;label&quot;&gt;Password&lt;/label&gt;
            &lt;div className=&quot;control&quot;&gt;
              &lt;input
                type=&quot;password&quot;
                placeholder=&quot;Enter password&quot;
                value={password}
                onChange={(e) =&gt; setPassword(e.target.value)}
                className=&quot;input&quot;
                required
              /&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;ErrorMessage message={errorMessage} /&gt;
          &lt;br /&gt;
          &lt;button className=&quot;button is-primary&quot; type=&quot;submit&quot;&gt;
            Register
          &lt;/button&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    );
  };
  
  export default Register;
  </code></pre>
  <p>Request:</p>
  <pre><code>XHRPOSThttp://localhost:3000/api/signup
  [HTTP/1.1 422 Unprocessable Entity 8ms]
  
      
  body    &quot;{\&quot;username\&quot;:\&quot;usertest\&quot;,\&quot;email\&quot;:\&quot;user@user.com\&quot;,\&quot;password\&quot;:\&quot;password\&quot;}&quot;
  headers {…}
  method  &quot;POST&quot;
  </code></pre>
  <p>Response:</p>
  <pre><code>{
      &quot;detail&quot;: [
          {
              &quot;loc&quot;: [
                  &quot;body&quot;,
                  &quot;username&quot;
              ],
              &quot;msg&quot;: &quot;field required&quot;,
              &quot;type&quot;: &quot;value_error.missing&quot;
          },
          {
              &quot;loc&quot;: [
                  &quot;body&quot;,
                  &quot;email&quot;
              ],
              &quot;msg&quot;: &quot;field required&quot;,
              &quot;type&quot;: &quot;value_error.missing&quot;
          },
          {
              &quot;loc&quot;: [
                  &quot;body&quot;,
                  &quot;password&quot;
              ],
              &quot;msg&quot;: &quot;field required&quot;,
              &quot;type&quot;: &quot;value_error.missing&quot;
          }
      ]
  }
  </code></pre>
  <p>From FastAPI backend Error:</p>
  <pre><code>INFO:     None:0 - &quot;POST /api/signup HTTP/1.1&quot; 422 Unprocessable Entity
  </code></pre>
  <p>I'm trying to create a simple signup form Backend FastAPI and serving Frontend in React. I've created the Pydantic Models for the body request but still getting this <code>422 Unprocessable Entity</code> error. How can I fix this?</p>
  <p>Update: It is working fine in Insomnia client when I hit the <code>POST</code> request it gives me the correct data with <code>200 OK</code> response.</p>
  <p>Thanks for any reply!</p>