Concept #142Easyextended-ai-concepts

What is the use of Swagger UI?

#gen-ai

Answer

What is Swagger UI?

Swagger UI is an open-source tool that automatically generates interactive API documentation from OpenAPI Specification (formerly Swagger) files. It lets developers explore and test REST APIs directly in a browser.

What Swagger UI Does

text
OpenAPI spec (YAML/JSON) → Swagger UI renders → Interactive docs in browser
  • Displays all API endpoints, methods, parameters
  • Shows request/response schemas
  • Lets you execute API calls directly in the browser
  • Auto-generates code examples in multiple languages

Quick Setup with FastAPI

FastAPI includes Swagger UI automatically at

text
/docs
:

python
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

app = FastAPI(
    title="AI Question API",
    description="API for managing Gen AI roadmap & core concepts",
    version="1.0.0"
)

class Question(BaseModel):
    id: int
    question: str
    difficulty: str
    tags: list[str]
    answer: Optional[str] = None

class QuestionCreate(BaseModel):
    question: str
    difficulty: str
    tags: list[str]

@app.get("/questions", response_model=list[Question], tags=["Questions"])
async def get_questions(
    difficulty: Optional[str] = None,
    tag: Optional[str] = None
):
    '''Get all questions with optional filtering by difficulty or tag'''
    # Implementation here
    return []

@app.get("/questions/{question_id}", response_model=Question, tags=["Questions"])
async def get_question(question_id: int):
    '''Get a specific question by ID'''
    return {"id": question_id, "question": "Example", "difficulty": "Medium", "tags": []}

@app.post("/questions", response_model=Question, status_code=201, tags=["Questions"])
async def create_question(question: QuestionCreate):
    '''Create a new question'''
    return {"id": 146, **question.dict(), "answer": None}

Run:

text
uvicorn main:app --reload

Access:

  • text
    http://localhost:8000/docs
    Swagger UI (interactive)
  • text
    http://localhost:8000/redoc
    → ReDoc (alternative docs)
  • text
    http://localhost:8000/openapi.json
    → Raw OpenAPI spec

Swagger UI Features

FeatureDescription
Try it outExecute real API calls from the browser
AuthorizationTest with API keys, Bearer tokens, OAuth
Schema explorerDrill into request/response models
Code samplesShows curl, Python, JS examples
ValidationShows required fields and formats
Response previewSee live API responses

OpenAPI Specification

Swagger UI renders from an OpenAPI spec:

yaml
# openapi.yaml
openapi: 3.0.0
info:
  title: My AI API
  version: 1.0.0

paths:
  /questions:
    get:
      summary: List all questions
      parameters:
        - name: difficulty
          in: query
          schema:
            type: string
            enum: [Easy, Medium, Hard]
      responses:
        '200':
          description: List of questions
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Question'

components:
  schemas:
    Question:
      type: object
      properties:
        id:
          type: integer
        question:
          type: string
        difficulty:
          type: string

Custom Swagger UI Configuration

python
from fastapi import FastAPI

app = FastAPI(
    title="Gen AI Learning API",
    description='''
## Gen AI Roadmap Concepts API

Access and manage 145+ Gen AI roadmap & core concepts.

### Features
- Search questions by difficulty and tags
- Get detailed answers
- Track progress
    ''',
    version="2.3.0",
    docs_url="/docs",          # Swagger UI URL
    redoc_url="/redoc",        # ReDoc URL
    openapi_url="/openapi.json"
)

Swagger vs Alternatives

ToolFormatBest For
Swagger UIOpenAPI 3.0REST APIs, most popular
ReDocOpenAPI 3.0Cleaner read-only docs
PostmanProprietaryTesting + documentation
InsomniaOpenAPIDesign-first API
StoplightOpenAPIEnterprise API platform