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.

Servers field in `openapi.json` not shown even after set `root_path`

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.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI
from fastapi.exceptions import HTTPException, RequestValidationError
from fastapi.responses import ORJSONResponse, RedirectResponse

app = FastAPI(
    root_path='/api/v1'
)

Description

I’m trying to run my API behind proxy. The proxy I’m used is apache2. The API is running smoothly (I’m running the API using gunicorn). But, when I tried to open the swagger docs using <domain>/api/v1/docs and test one of the function, it’s not working properly. And I realize that servers parameter in openapi.json is not shown. It should be like this:

{
    "openapi": "3.0.2",
    "servers": [
        {"url": "/api/v1"}
    ],
    ...
}

But, what is shown is like this

{
    "openapi": "3.0.2",
    ...
}

I think this is why when I test the API from the swagger docs, the test is not working properly.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.68.1

Python Version

3.9.6

Additional Context

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
fahadh4ilyascommented, Sep 27, 2021

Ah, I get it now. This is because custom_openapi. I have to add servers=app.servers inside get_openapi.

0reactions
fahadh4ilyascommented, Sep 27, 2021

Dumbing it down works. I only use this script as main

from fastapi import FastAPI

app = FastAPI(
    root_path='/api/v1',
    servers=[{'url': '/api/v1'}]
)

@app.get('/')
async def hello():

    return {'result': 'Hello, World!'}

My real API using this parameter for app:

  • title
  • description
  • openapi_tags value as list of dictionary
  • default_response_class value as ORJSONResponse
  • responses to set model for 504 status code

I also add FastAPILimiter. and custom the openapi using this

app.openapi = custom_openapi(app)

where custom_openapi is this

def custom_openapi(app: FastAPI):
    def wrapper():
        if app.openapi_schema:
            return app.openapi_schema
        openapi_schema = get_openapi(
            title=app.title,
            description=app.description,
            version=app.version,
            routes=app.routes,
            tags=app.openapi_tags
        )

        http_methods = ["post", "get", "put", "delete"]
        # look for the error 422 and removes it
        for method in openapi_schema["paths"]:
            for m in http_methods:
                try:
                    del openapi_schema["paths"][method][m]["responses"]["422"]
                except KeyError:
                    pass
                # try:
                #     if openapi_schema["paths"][method][m]["responses"]["200"]['description'] == 'Successful Response':
                #         del openapi_schema["paths"][method][m]["responses"]["200"]
                # except KeyError:
                #     pass
        for schema in list(openapi_schema["components"]["schemas"]):
            if schema in ["HTTPValidationError", "ValidationError"]:
                del openapi_schema["components"]["schemas"][schema]

        app.openapi_schema = openapi_schema
        return app.openapi_schema
    return wrapper
Read more comments on GitHub >

github_iconTop Results From Across the Web

Behind a Proxy - FastAPI
Because we have a proxy with a path prefix of /api/v1 for our app, the frontend needs to fetch the OpenAPI schema at...
Read more >
API Server and Base Path - Swagger
In OpenAPI 3.0, you use the servers array to specify one or more base URLs for your API. servers replaces the host ,...
Read more >
Using OpenAPI and Swagger UI - Quarkus
The solution is located in the openapi-swaggerui-quickstart directory. Creating the Maven project. First, we need a new project. Create a new project with...
Read more >
F.A.Q - Springdoc-openapi
POJO object must contain getters for fields with mandatory prefix get . Otherwise, the swagger documentation will not show the fields of the...
Read more >
How set default API definition url in openapi? - Stack Overflow
With the latest version of springdoc-openapi-ui for me, it was 1.6.7 I updated my spring boot application config YAML to the following and...
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