DEV Community

Cover image for Replacing fastapi's default api docs with elements
Amal Shaji
Amal Shaji

Posted on • Originally published at amal.sh

4 1 1

Replacing fastapi's default api docs with elements

By default, fastapi comes with swagger for API testing and redoc for API documentation. Let's replace them with elements, a pretty API documentation tool.

Turn off the defaults

Turn off the default documentation by setting it to None



app = FastAPI(
    docs_url=None, redoc_url=None
)


Enter fullscreen mode Exit fullscreen mode

Add the new docs view



@app.get("/docs", include_in_schema=False)
async def api_documentation(request: Request):
    return HTMLResponse("""
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Elements in HTML</title>

    <script src="https://unpkg.com/@stoplight/elements/web-components.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css">
  </head>
  <body>

    <elements-api
      apiDescriptionUrl="openapi.json"
      router="hash"
    />

  </body>
</html>""")


Enter fullscreen mode Exit fullscreen mode

Navigate to /docsYou should see something like this

demo

References

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
ronifintech profile image
Roni Yosofov

I had to register to say THANK YOU!
Didn't know I could replace Swagger so easily!
elements is awesome!

Collapse
 
inayet profile image
Inayet Hadi

Exactly what I was looking for, thank you so much

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay