Search code examples
pythonswaggerfastapiopenapiswagger-ui

How to merge swagger documentation using FastAPI?


I have two FastAPI services running on different ports:

from fastapi import FastAPI

app = FastAPI()


@app.get("/test")
async def root():
    return {"message": "Hello World"}


@app.get("/test/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

version: '3.9'
services:

  first:
    build:
      context: ./first
      dockerfile: Dockerfile
    ports:
      - "8000:8000"

  second:
    build:
      context: ./second
      dockerfile: Dockerfile
    ports:
      - "9000:9000"

I need one endpoint where I can select services with the documentation I need, something like this: enter image description here

How can I combine the swagger documentation for these services? The documentation for FastAPI says that you can make a custom one, but I don’t know how to combine them into one endpoint.


Solution

  • I cloned the official repository https://github.com/swagger-api/swagger-ui. I created a separate service, moved the /dist folder to it and changed the paths in the swagger-initializer.js file:

    window.onload = function() {
     //<editor-fold desc="Changeable Configuration Block">
    
     // the following lines will be replaced by docker/configurator, when it 
    runs in a docker-container
     window.ui = SwaggerUIBundle({
        urls: [
          {url: "http://localhost:8000/openapi.json", name: "First Service"},
          {url: "http://localhost:9000/openapi.json", name: "Second Service"},
        ],
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout"
     });
     //</editor-fold>
    };
    

    Added Dockerfile

    FROM node:14
    RUN npm install -g http-server
    COPY . /usr/share/nginx/html
    CMD ["http-server", "/usr/share/nginx/html", "-p", "80"]
    

    And I got this interface: enter image description here