简体   繁体   中英

How to redirect FastAPI Documentation while running on Docker

I need to redirect " /swagger-ui.html " to the documentation page.

I tried:

app = FastAPI()

@app.get("/swagger-ui.html")
async def docs_redirect():
    response = RedirectResponse(url='/docs')
    return response

and

app = FastAPI(docs_url="/swagger-ui.html")

@app.get("/")
async def docs_redirect():
    response = RedirectResponse(url='/swagger-ui.html')
    return response

But, running the project directly (using uvicorn command) I works, but when I put it on a Docker container, it outputs this message on the browser, asking for the location, where nothing works as input:

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For eg if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/ . Please enter the location manually:

Here's my dockerfile:

FROM python:3.8
USER root
RUN mkdir -p /usr/local/backend
WORKDIR /usr/local/backend
EXPOSE 8080
ARG BUILD_ENV=dev 
ENV BUILD_ENV=$BUILD_ENV
COPY . /usr/local/backend
RUN pip install -r requirements.txt
ENTRYPOINT ["uvicorn", "app.main:app", "--port", "8080"]

Try this code, it works for me when I use docker-compose :

app = FastAPI()

@app.get("/")
async def docs_redirect():
    return RedirectResponse(url='/docs')

To avoid showing the redirect in the docs page

@app.get("/", include_in_schema=False)
async def docs_redirect():
    return RedirectResponse(url='/docs')

Documentation here: https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#exclude-from-openapi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM