[Python] Webhook listener in FastAPI raises 422 Unprocessable Entity error [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    I have a webhook listener that uses an APIRouter to designate the route for the application on the FastAPI server. The app should receive a POST request (expecting data in JSON format) and log this to the console. However, I am getting consistent redirects. I have attempted the following with curl:

    curl -X 'POST' \
    'http://127.0.0.1:8010/webhook' \
    -H 'accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{"data": {"UK":"test"}}'


    The listener:

    import hmac
    from logging import Logger, info
    from fastapi import APIRouter, FastAPI, Header, Request, Response
    from router.router1 import rout
    from pydantic import BaseModel

    WEBHOOK_SECRET = '123-456-789'

    class WebhookResponse(BaseModel):
    result: str

    class WebhookData(BaseModel):
    body: dict

    app = FastAPI()
    rout = APIRouter()

    @app.get("/")
    async def welcome() -> dict:
    return { "message": 'Hello World!' }

    def printLog(data):
    info(f"Raw data: {data}")

    @rout.post("/webhook", response_model=WebhookResponse, status_code=200)
    async def webhook(
    webhook_input: WebhookData,
    request: Request,
    response: Response,
    content_length: int = Header(...),
    x_hook_signature: str = Header(None)
    ):
    if content_length > 1_000_000:
    # To prevent memory allocation attacks
    Logger.error(f"Content too long ({content_length})")
    response.status_code = 400
    return {"result": "Content too long"}
    if x_hook_signature:
    raw_input = await request.body()
    input_hmac = hmac.new(
    key=WEBHOOK_SECRET.encode(),
    msg=raw_input,
    digestmod="sha512"
    )
    if not hmac.compare_digest(
    input_hmac.hexdigest(),
    x_hook_signature
    ):
    Logger.error("Invalid message signature")
    response.status_code = 400
    return {"result": "Invalid message signature"}
    Logger.info("Message signature checked ok")
    else:
    Logger.info("No message signature to check")
    printLog(webhook_input)
    return {"result": "ok"}

    app.include_router(rout)


    Curl prints out the following error:

    {
    "detail": [
    {
    "loc": [
    "body"
    ],
    "msg": "value is not a valid dict",
    "type": "type_error.dict"
    }
    ]
    }


    With the following printed to console:

    INFO: 127.0.0.1:50192 - "POST /webhook/ HTTP/1.1" 422 Unprocessable Entity

    Continue reading...

Compartilhe esta Página