Open In App

Documenting Websocket APIs with Swagger

Last Updated : 17 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

WebSocket APIs offer a powerful way to create real-time, interactive applications by enabling bidirectional communication between clients and servers. Documenting these APIs is crucial for developers to understand and utilize them effectively. Swagger (now known as OpenAPI) is a widely used framework for API documentation, but it primarily focuses on HTTP-based APIs. This article will explore how to document WebSocket APIs using Swagger in a Python environment.

Understanding WebSocket APIs

Before diving into the documentation process, let's briefly understand what WebSocket APIs are. WebSockets provide a full-duplex communication channel over a single, long-lived connection between a client and a server. This is ideal for applications that require real-time updates, such as chat applications, online gaming, live sports updates, and collaborative platforms.

Setting Up Swagger for Python

Swagger can be integrated with Python applications using tools like Flask and FastAPI. Both frameworks have extensive support for Swagger documentation out of the box, though they are traditionally used for HTTP APIs. To start, you'll need to install the required libraries:

pip install fastapi uvicorn

Creating a WebSocket API with FastAPI

Here's a simple WebSocket API built with FastAPI:

Python
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse

app = FastAPI()

html = """
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Test</title>
</head>
<body>
    <h1>WebSocket Test</h1>
    <form id="form">
        <input type="text" id="messageInput" autocomplete="off"/>
        <button>Send</button>
    </form>
    <ul id="messages"></ul>
    <script>
        const form = document.getElementById('form');
        const input = document.getElementById('messageInput');
        const messages = document.getElementById('messages');

        const ws = new WebSocket('ws://localhost:8000/ws');

        ws.onmessage = function(event) {
            const li = document.createElement('li');
            li.textContent = event.data;
            messages.appendChild(li);
        };

        form.addEventListener('submit', function(event) {
            event.preventDefault();
            ws.send(input.value);
            input.value = '';
        });
    </script>
</body>
</html>
"""

@app.get("/")
async def get():
    return HTMLResponse(html)

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

This example sets up a simple WebSocket server with a basic HTML client to send and receive messages.

Documenting the WebSocket API with Swagger

Swagger is primarily used for documenting RESTful APIs, but we can still leverage its features to provide comprehensive documentation for our WebSocket endpoints.

Creating an OpenAPI Specification

To document our WebSocket API, we can include details in the OpenAPI specification provided by FastAPI. Although OpenAPI does not natively support WebSocket, we can add descriptions and examples in the documentation.

Python
from fastapi.openapi.utils import get_openapi

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="WebSocket API",
        version="1.0.0",
        description="This is a simple WebSocket API",
        routes=app.routes,
    )
    openapi_schema["paths"]["/ws"] = {
        "get": {
            "summary": "WebSocket connection",
            "description": "Connect to the WebSocket server. Send a message and receive a response.",
            "responses": {
                "101": {
                    "description": "Switching Protocols - The client is switching protocols as requested by the server.",
                }
            }
        }
    }
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

In this example, we override FastAPI's default OpenAPI generation to include a description of our WebSocket endpoint. This approach provides developers with a clear understanding of how to interact with the WebSocket server.

Running and Testing the Documentation

To run the FastAPI application with the custom documentation:

uvicorn your_app:app --reload

Visit http://localhost:8000/docs to see the interactive Swagger UI with your custom documentation.

Output

Capture-ezgifcom-resize-(1)




Next Article
Article Tags :
Practice Tags :

Similar Reads