question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Include possible HTTPExceptions in OpenAPI spec

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here’s a self-contained, minimal, reproducible, example with my use case:

from fastapi import FastAPI, HTTPException

app = FastAPI()


@app.get("/")
def read_root(gimme_coffee: bool = False):
    if gimme_coffee:
        raise HTTPException(status_code=418, detail="I'm a teapot.")
    return {"Hello": "World"}

Description

  • Open the browser and call the endpoint /docs
  • Note that the only listed response codes are 200 and 422
  • Execute the route with gimme_coffee set to true and note that it returns a 418 status code

How do I set the status code for 418 in the OpenAPI docs? I was expecting to be able to pass in a list of possible HTTPExceptions and have them be automatically converted, but there does not appear to be any way to do that. The closest thing I found was Additional Status Codes but that seemed at best tangentially relevant since I am raising HTTPExceptions, not looking to build out a custom exception JSON response.

Properly documenting error states is just as important as documenting the success state. I really hope FastAPI provides an easy way to do this.

Environment

  • OS: Linux (Docker container using standard python-3.8 image)
  • FastAPI Version: 0.61.1
  • Python version: 3.8.5

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:10
  • Comments:11 (3 by maintainers)

github_iconTop GitHub Comments

9reactions
onecrayoncommented, Nov 30, 2020

@ycd Per my comment here, that’s what I’m doing. It’s also unnecessary code duplication. My feature request is for an easy way to pass in children of HTTPException and just have FastAPI automatically figure out what the error output should look like. So for example here’s some pseudo-code that’s based on my current project:

from fastapi import status, HTTPException

class APIException(HTTPException):
    """Light wrapper around HTTPException that allows specifying defaults via class property"""

    status_code = status.HTTP_400_BAD_REQUEST
    detail = None
    headers = None

    def __init__(self, *args, **kwargs):
        if "status_code" not in kwargs:
            kwargs["status_code"] = self.status_code
        if "detail" not in kwargs:
            kwargs["detail"] = self.detail
        if "headers" not in kwargs:
            kwargs["headers"] = self.headers
        super().__init__(*args, **kwargs)

class TeapotException(APIException):
    status_code = 418
    detail = "I'm a teapot."

@app.get("/")
def read_root(gimme_coffee: bool = False, response_exceptions=[TeapotException]):
    if gimme_coffee:
        raise TeapotException()
    return {"Hello": "World"}

Even better would be to have FastAPI able to introspect the method and look for HTTPException-derived exceptions to auto-populate the list, but that’s possibly edging a little too far into magical territory.

In any case, it’s silly that I can have FastAPI automatically discover query params and such based on passed classes, but need to explicitly duplicate all of the information that’s already stored in my exception classes in order to document exceptions.

4reactions
Kludexcommented, Apr 30, 2021
Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI allow specific parameter values in OpenAPI ...
I want to allow the strings "a" "b" and "c" as possible parameter values. I want these values to show up in the...
Read more >
Describing Responses
An API specification needs to specify the responses for all API operations. Each operation must have at least one response defined, usually a...
Read more >
Handling Errors - FastAPI
The client doesn't have enough privileges for that operation. ... To return HTTP responses with errors to the client you use HTTPException ....
Read more >
422 Unprocessable Entity - HTTP - MDN Web Docs
Specifications. Specification. HTTP Semantics # status.422. Found a problem with this page? ... Want to fix the problem yourself?
Read more >
API with NestJS #4. Error handling and data validation
API with NestJS #60. The OpenAPI specification and Swagger; 61. ... NestJS has a set of exceptions that extend the HttpException.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found