Claude
Skills
Sign in
Back

code-to-oas

Included with Lifetime
$97 forever

Analyze an entire API codebase and generate an accurate OpenAPI Specification (OAS 3.0) file from the source code. Use this skill whenever the user wants to generate, create, or derive an OpenAPI spec from code, reverse-engineer an API definition, or document an existing API. Triggers on phrases like "generate OAS from code", "create OpenAPI spec", "document my API", "reverse-engineer spec", "write openapi.json from my codebase", or any request to produce an OAS file by reading source files rather than an existing spec.

Backend & APIs

What this skill does


# API source code to OpenAPI Specification

Analyzes an API codebase — regardless of language or framework — and produces
a complete, valid **OpenAPI 3.0.x** specification file (`openapi.json`) from
the source code. No existing OAS file is required.

---

## Entry Point

1. **Identify the root directory.** Use the directory the user specifies, or
   default to the current working directory. If a specific service subdirectory
   is open in the editor, use that.

2. **Detect the language and framework.** Scan for indicators without opening
   every file yet:
   - `package.json` → Node.js. Check `dependencies` for `express`, `fastify`,
     `koa`, `hapi`, `nestjs`, `@nestjs/core`.
   - `requirements.txt` / `pyproject.toml` / `setup.py` → Python. Check for
     `fastapi`, `flask`, `django`, `starlette`, `tornado`.
   - `pom.xml` / `build.gradle` → Java/Kotlin. Check for `spring-boot`,
     `quarkus`, `micronaut`.
   - `go.mod` → Go. Check for `gin`, `echo`, `chi`, `gorilla/mux`, `fiber`.
   - `Gemfile` → Ruby. Check for `rails`, `sinatra`, `grape`.
   - `*.csproj` / `*.sln` → C#/.NET. Check for `AspNetCore`, `WebApi`.
   - Any existing partial OAS file (e.g. `openapi.yaml`, `swagger.json`) —
     read it and use it as a starting scaffold, then extend/correct it.

3. **Announce the plan.**
   > "I'll analyze the codebase as a `<framework>` API and generate
   > `openapi.json`. I'll read route files, middleware, and model definitions.
   > This may take a moment."

4. **Execute the analysis** (Steps 1–8 below), then write the OAS file.

---

## Step 1 — Discover Route / Controller Files

Locate the files that define HTTP routes or controllers. Use glob and grep
patterns matched to the detected framework:

| Framework | Look for |
|---|---|
| **Express** | Files importing `express.Router()`, `app.get/post/put/delete/patch` |
| **FastAPI** | Files with `@app.get`, `@router.get`, `APIRouter()` |
| **Flask** | Files with `@app.route`, `@blueprint.route` |
| **Django** | `urls.py` files, `path()` / `re_path()` / `url()` calls |
| **NestJS** | Files with `@Controller`, `@Get`, `@Post`, `@Put`, `@Delete`, `@Patch` |
| **Spring** | Files with `@RestController`, `@RequestMapping`, `@GetMapping`, etc. |
| **Gin/Echo/Chi** | Files calling `r.GET`, `r.POST`, `e.GET`, `r.Route`, `chi.NewRouter()` |
| **Rails** | `config/routes.rb` |
| **Sinatra/Grape** | Files with `get '/'`, `post '/'`, `resource :name` |

Read every discovered route file in full. For each route, record:
- HTTP method (`GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS`)
- Path string (convert framework-specific syntax to OAS path syntax:
  `:param` → `{param}`, `<param>` → `{param}`, `{param:int}` → `{param}`)
- Handler function name (use as a seed for `operationId`)
- Middleware applied to this route or router group

---

## Step 2 — Extract Operation Details from Handlers

For each route handler identified in Step 1, read the handler implementation.
Extract:

### Path Parameters
Any segment in the path like `{id}` is a path parameter. It must appear in
`parameters` with `in: path` and `required: true`.

### Query Parameters
Look for:
- Express: `req.query.foo`, destructuring `const { foo } = req.query`
- FastAPI: function arguments without `Body()` annotation and not in the path
- Flask: `request.args.get('foo')`
- Django: `request.GET.get('foo')`
- Spring: `@RequestParam`
- Go: `c.Query("foo")`, `r.URL.Query().Get("foo")`

### Request Body
Look for:
- Express: `req.body`, `req.body.foo`
- FastAPI: `Body()` annotated params, Pydantic model params
- Flask: `request.json`, `request.get_json()`
- Django: `request.data`, `request.POST`
- Spring: `@RequestBody`
- Go: `c.ShouldBindJSON()`, `json.NewDecoder(r.Body)`

### Response Structure
Look for:
- `res.json({...})`, `res.status(200).json({...})` (Express)
- `return {...}` with type annotations (FastAPI)
- `jsonify({...})` (Flask)
- `Response(data, ...)` (Django REST)
- `return ResponseEntity<>` (Spring)
- `c.JSON(200, ...)` (Gin)

Note every distinct status code sent and the shape of each response body.

### Headers
Look for authentication headers read from the request:
- `req.headers['authorization']`, `req.headers.authorization`
- `Authorization: Bearer` checks
- Custom headers like `x-api-key`, `x-user-id`

---

## Step 3 — Identify Authentication / Middleware

Read all middleware files. Look for:
- JWT verification middleware → `securityScheme` type `http`, scheme `bearer`,
  `bearerFormat: JWT`
- API key middleware checking a header → `securityScheme` type `apiKey`,
  `in: header`
- API key middleware checking a query param → `securityScheme` type `apiKey`,
  `in: query`
- Basic auth → `securityScheme` type `http`, scheme `basic`
- OAuth2 / OIDC → `securityScheme` type `oauth2` or `openIdConnect`
- Session / cookie auth → `securityScheme` type `apiKey`, `in: cookie`

For each route, determine whether authentication middleware is applied:
- Applied at the router/blueprint level (affects all routes in that group)
- Applied per-route
- Excluded via an allowlist (e.g. `/login`, `/register` are public)

Map each route to: **authenticated** (list the security scheme) or **public**
(no `security` requirement, or `security: [{}]`).

---

## Step 4 — Discover Data Models / Schemas

Locate model, schema, or DTO definitions:

| Framework | Source |
|---|---|
| **Express + Mongoose** | `mongoose.Schema({...})` definitions |
| **Express + Sequelize** | `sequelize.define(...)` or class models |
| **Express + TypeORM** | `@Entity` class definitions |
| **FastAPI** | Pydantic `BaseModel` subclasses |
| **Flask + SQLAlchemy** | `db.Model` subclasses |
| **Django** | `models.Model` subclasses, `serializers.Serializer` subclasses |
| **Spring** | `@Entity`, `@Document`, DTO/POJO classes |
| **Go** | `type Foo struct { ... }` with JSON tags |
| **Rails** | ActiveRecord model files, serializer files |

For each model/schema, extract:
- All fields with their types
- Required vs optional fields
- Validation constraints: `minLength`, `maxLength`, `minimum`, `maximum`,
  `pattern`, `enum`, etc.
- Relationships (for reference, not fully expanded in OAS)

Map framework types to OAS types:

| Framework type | OAS `type` + `format` |
|---|---|
| `String` / `str` / `string` | `type: string` |
| `Number` / `float` / `Float` | `type: number, format: float` |
| `Int` / `int` / `Integer` / `Long` | `type: integer, format: int64` |
| `Boolean` / `bool` | `type: boolean` |
| `Date` / `DateTime` / `datetime` | `type: string, format: date-time` |
| `Buffer` / `bytes` / `BinaryField` | `type: string, format: binary` |
| `Array` / `List` / `[]Type` | `type: array, items: <schema>` |
| `Object` / `Dict` / `Map` | `type: object` |
| `ObjectId` / `UUID` / `uuid` | `type: string, format: uuid` |
| `Email` / `EmailStr` | `type: string, format: email` |
| Enum | `type: string, enum: [...]` |

---

## Step 5 — Discover Server Configuration

Find the server's base URL and port:
- Express: `app.listen(PORT)` — check `PORT` env var and its default value
- FastAPI: `uvicorn.run(app, host=..., port=...)` or `Dockerfile`/`docker-compose.yml`
- Django: `ALLOWED_HOSTS`, `runserver` port
- Spring: `server.port` in `application.properties`/`application.yml`
- Go: `http.ListenAndServe(":PORT", ...)`
- Check `docker-compose.yml`, `.env`, `Dockerfile`, `Makefile` for exposed ports

Check for a URL prefix applied to all routes:
- Express: `app.use('/api/v1', router)`
- FastAPI: `app.include_router(router, prefix='/api/v1')`
- Django: `path('api/v1/', include(urlpatterns))`
- Spring: `@RequestMapping('/api/v1')`

Record: base URL (e.g. `http://localhost:3000`) and any API prefix
(e.g. `/api/v1`).

---

## Step 6 — Read Supporting Files

Read any existing documentation, README, or config that gives API context:
- `README.md` — API description, versioning, authentication instructions
- Existing partial `openapi.yaml` / `swagger.json` — scaffold to extend
- `CHANGELOG.md` — API version history
- `.en

Related in Backend & APIs