Fastapi: best way to raise duplicate field entry exception

Created on 24 Aug 2020  路  5Comments  路  Source: tiangolo/fastapi

Hi, I have a lots of unique fields in my database and I want to raise HTTPException with proper detail for each field that is duplicated.
what is the best way to do it?

question

Most helpful comment

Thanks for the help here everyone! :clap: :bow:

Thanks for reporting back and closing the issue :+1:

All 5 comments

From the Documentation.

You are able to Override the default HTTPException class, to create your own custom implementation matching your use case.

However, there is also the use case of wanting to just provide the error, without having to make your own, which can be done via Inheriting the RequestValidatonError.

Implementing how they are dealt with or processed is purely on your application.

You can raise a duplicate error with RequestValidationError

from fastapi import Request, status, FastAPI
from fastapi.responses import JSONResponse
from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.exceptions import RequestValidationError
...
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse({"Invalid body": {"body": exc.body}})

This will return

{"Invalid body":{"body":{}}}

But if you want to check them manually and raise a manual HTTPException you can go for this

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    body = jsonable_encoder(exc)
    return JSONResponse({"body": body})


@app.post("/")
async def endpoint(body: BodyModel, request: fastapi.Request):
    if body.msg == "fail this":
        raise HTTPException(status_code=404, detail=body)
    return body

This will also return

{
  "body": {
    "status_code": 404,
    "detail": {
      "msg": "fail this"
    },
    "headers": null
  }
}

The way I've interpreted the question, none of the above answers suits as answer for the question issue. The way I've interpreted is: "If I have a model on which I have unique constrains and I try to create a database object that is not allowed, how can I let the user know about it?"

If I've interpreted right and you're using SQLAlchemy:

  • When you try to create an object and it has constrains, SQLAlchemy will raise as IntegrityError with a description about what is duplicated.

What you can do:

  • Except that exception, strip the values you want and raise a HTTPException from your endpoint function with the data you want.

Notes:

  • Create your own exception is a good practice.
  • If I've interpreted the question wrongly, ignore this ;)

@Kludex that's exactly what I was asking for. thank you.

Thanks for the help here everyone! :clap: :bow:

Thanks for reporting back and closing the issue :+1:

Was this page helpful?
0 / 5 - 0 ratings