[Python] How to customize error response in FastAPI?

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following FastAPI backend:

    from fastapi import FastAPI

    app = FastAPI

    class Demo(BaseModel):
    content: str = None

    @app.post("/demo")
    async def demoFunc(d:Demo):
    return d.content


    The issue is that when I send a request to this API with extra data like:

    data = {"content":"some text here"}aaaa


    or

    data = {"content":"some text here"aaaaaa}

    resp = requests.post(url, json=data)


    it throws an error with status code 422 unprocessable entity error with Actual("some text here") and Extra("aaaaa") data in the return field in case of data = {"content":"some text here"}aaaa:

    {
    "detail": [
    {
    "loc": [
    "body",
    47
    ],
    "msg": "Extra data: line 4 column 2 (char 47)",
    "type": "value_error.jsondecode",
    "ctx": {
    "msg": "Extra data",
    "doc": "{\n \"content\": \"some text here\"}aaaaa",
    "pos": 47,
    "lineno": 4,
    "colno": 2
    }
    }
    ]
    }


    I tried to put the line app=FastAPI() in a try-catch block, however, it doesn't work. Is there any way I can handle this issue with own response instead of the above mentioned auto response? Something like this:

    {"error": {"message": "Invalid JSON body"},
    "status": 0}

    Continue reading...

Compartilhe esta Página