Skip to content

Custom RequestValidationError Handling Overwritten in stac-fastapi #720

@joshimai

Description

@joshimai

In our FastAPI application using stac-fastapi, we encountered an issue where the RequestValidationError handling gets overwritten if it is registered before the creation of StacApi.

Sample Code Demonstrating the Error:

from fastapi import FastAPI, Request
from stac_fastapi.api.app import StacApi
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from stac_fastapi.types.config import ApiSettings
from stac_fastapi.pgstac.core import CoreCrudClient
from stac_fastapi.extensions.core import (
    FieldsExtension,
    ContextExtension,
    QueryExtension,
    SortExtension,
)

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse(
        status_code=400,
        content={"customerrordetail": exc.errors(), "body": exc.body},
    )

extensions = [FieldsExtension(), ContextExtension(), QueryExtension(), SortExtension()]

PCClient = CoreCrudClient()
settings = ApiSettings()

# First initialization of StacApi
stac_api = StacApi(
    app=app,
    settings=settings,
    extensions=extensions,
    client=PCClient,
    exceptions={},
    middlewares=[],
)

# Test route to trigger RequestValidationError
@app.post("/items/")
async def create_item(item: dict):
    return item

Steps to Reproduce:

uvicorn main:app --reload
curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" 

Expected Behavior:
{"customerrordetail":[{"type":"missing","loc":["body"],"msg":"Field required","input":null}],"body":null}

Actual Behavior:
{"code":"RequestValidationError","description":"[{'type': 'missing', 'loc': ('body',), 'msg': 'Field required', 'input': None}]"}

Workaround:
To avoid the issue, the RequestValidationError handling must be registered after StacApi creation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions