[Python] Python: FastAPI error 422 with POST request when sending JSON data

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm building a simple API to test a database. When I use GET request everything works fine, but if I change to POST, I get 422 Unprocessable Entity error.

    Here is the FastAPI code:

    from fastapi import FastAPI

    app = FastAPI()

    @app.post("/")
    def main(user):
    return user


    Then, my request using JavaScript

    let axios = require('axios')

    data = {
    user: 'smith'
    }

    axios.post('http://localhost:8000', data)
    .then(response => (console.log(response.url)))


    Also, using Python requests:

    import requests

    url = 'http://127.0.0.1:8000'
    data = {'user': 'Smith'}

    response = requests.post(url, json=data)
    print(response.text)


    I also tried to parse as JSON, enconding using utf-8, and change the headers, but nothing worked for me.

    Continue reading...

Compartilhe esta Página