Skip to content

Commit 2d10c80

Browse files
committed
Complete middleware reference and openapi-docs chapter
1 parent 84b49a7 commit 2d10c80

File tree

12 files changed

+349
-34
lines changed

12 files changed

+349
-34
lines changed

docs/guide/web/_meta.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
"route",
33
"validator",
44
"response",
5-
"middleware",
65
"openapi-docs",
76
"configuration",
87
"project"

docs/guide/web/middleware.md

Lines changed: 0 additions & 19 deletions
This file was deleted.

docs/guide/web/openapi-docs.md

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,207 @@
11
# OpenAPI and Docs
22

3+
AIScript provides automatic OpenAPI documentation generation from your route definitions with zero configuration. This feature creates comprehensive API documentation including type information, validation rules, and examples derived directly from your code.
4+
5+
## Basic Documentation
6+
7+
The simplest way to document your API is through docstrings. In AIScript, you can use triple-quoted strings (`"""..."""`) to provide documentation for routes and their parameters:
8+
9+
```py
10+
post /api/chat {
11+
"""
12+
Chat API endpoint
13+
14+
Sends a message to the chat service and returns a response.
15+
"""
16+
17+
body {
18+
"""The message to be sent to the chat service"""
19+
message: str,
20+
}
21+
22+
return "Input: " + body.message + "!";
23+
}
24+
```
25+
26+
## Documenting Routes
27+
28+
Each route can have a detailed description:
29+
30+
```py
31+
get /api/users {
32+
"""
33+
List all users
34+
35+
Returns a paginated list of all users in the system.
36+
Results can be filtered by role or status.
37+
"""
38+
39+
query {
40+
@number(min=1)
41+
"""Page number for pagination"""
42+
page: int = 1,
43+
44+
@number(min=1, max=100)
45+
"""Number of items per page"""
46+
limit: int = 20
47+
}
48+
49+
// Route implementation
50+
}
51+
```
52+
53+
## Documenting Parameters
54+
55+
You can document query parameters, path parameters, and request body fields:
56+
57+
### Query Parameters
58+
59+
```py
60+
get /api/products {
61+
query {
62+
"""Filter products by category"""
63+
category: str,
64+
65+
"""Sort order (asc or desc)"""
66+
@in(["asc", "desc"])
67+
sort: str = "asc",
68+
69+
"""Minimum price filter"""
70+
@number(min=0)
71+
min_price: float
72+
}
73+
}
74+
```
75+
76+
### Path Parameters
77+
78+
```py
79+
get /api/users/<id:int> {
80+
"""
81+
Get user by ID
82+
83+
Retrieves detailed information about a specific user.
84+
85+
Parameters:
86+
id: The unique identifier of the user
87+
"""
88+
89+
// Route implementation
90+
}
91+
```
92+
93+
### Request Body
94+
95+
```py
96+
post /api/products {
97+
@json
98+
body {
99+
"""Product name (must be unique)"""
100+
@string(min_len=3, max_len=100)
101+
name: str,
102+
103+
"""Detailed product description"""
104+
description: str,
105+
106+
"""Product price in USD"""
107+
@number(min=0.01)
108+
price: float,
109+
110+
"""Product categories (at least one required)"""
111+
@array(min_items=1)
112+
categories: array
113+
}
114+
}
115+
```
116+
117+
## Response Documentation
118+
119+
You can document the responses a route might return:
120+
121+
```py
122+
get /api/orders/<id:int> {
123+
"""
124+
Get order details
125+
126+
Retrieves the details of a specific order.
127+
128+
Responses:
129+
200: Successful operation
130+
404: Order not found
131+
403: Unauthorized access
132+
"""
133+
134+
// Route implementation
135+
}
136+
```
137+
138+
## Auto-Generated Documentation
139+
140+
AIScript automatically generates OpenAPI documentation based on your route definitions. This documentation includes:
141+
142+
1. All routes and their HTTP methods
143+
2. Request parameters (query, path, body)
144+
3. Validation rules applied to parameters
145+
4. Data types for all parameters and responses
146+
5. Docstrings as descriptions
147+
6. Documentation specific to each parameter
148+
149+
## Accessing Documentation
150+
151+
By default, AIScript makes your API documentation available at `/redoc` and the OpenAPI specification at `/openapi.json`. You can customize these paths in your project configuration:
152+
153+
```toml
154+
# project.toml
155+
156+
[apidoc]
157+
enabled = true
158+
type = "redoc"
159+
path = "/redoc"
160+
```
161+
162+
AIScript's documentation UI support **Swagger UI** and **Redoc**.
163+
164+
## Tags and Grouping
165+
166+
You can use tags to group related endpoints in the documentation:
167+
168+
```py
169+
@docs(tag = "Users")
170+
get /api/users {
171+
"""List all users"""
172+
}
173+
174+
@docs(tag = "Users")
175+
get /api/users/<id:int> {
176+
"""Get user by ID"""
177+
}
178+
179+
@docs(tag = "Users")
180+
get /api/products {
181+
"""List all products"""
182+
}
183+
```
184+
185+
## Hiding Endpoints
186+
187+
You can exclude specific endpoints from documentation:
188+
189+
```py
190+
@docs(hidden=true)
191+
get /internal/metrics {
192+
"""This endpoint won't appear in documentation"""
193+
}
194+
```
195+
196+
## Benefits
197+
198+
Automatic OpenAPI documentation in AIScript offers several benefits:
199+
200+
1. **Zero configuration**: Documentation is generated automatically from your code
201+
2. **Always up-to-date**: Documentation updates whenever your code changes
202+
3. **Complete type information**: All parameter types are accurately reflected
203+
4. **Validation rules included**: All validators are documented
204+
5. **Interactive testing**: Test endpoints directly from the documentation UI
205+
6. **Client generation**: Use the OpenAPI spec to generate client libraries in various languages
206+
207+
AIScript's built-in documentation system ensures your API is well-documented with minimal effort, making it easier for both you and your API consumers to understand and use your services.

docs/reference/configuration/ai.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# AI
2+
13
> For AI observability, please refer to [observability](./observability.md).
24
35
```toml

docs/reference/configuration/auth.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# Auth
2+
13
```toml
24
[auth.jwt]
35
secret = "$JWT_SECRET"

docs/reference/configuration/database.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# Database
2+
13
```toml
24
[database.pinecone]
35
api_key = "YOUR_API_KEY"

docs/reference/configuration/general.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# General
12

23
```toml
34
[project]
Lines changed: 111 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,128 @@
1+
# Middleware
2+
3+
Middleware in AIScript provides a powerful way to process HTTP requests and responses. Middleware functions are executed in a sequence, allowing you to modify requests, validate authentication, log activities, and more before a route handler is invoked.
4+
5+
## CORS
6+
7+
Controls Cross-Origin Resource Sharing settings.
18

29
```toml
10+
# project.toml
11+
312
[middleware.cors]
4-
allowed_origins = ["http://localhost:3000"]
13+
allowed_origins = ["http://localhost:3000", "https://example.com"]
514
allowed_methods = ["GET", "POST", "PUT", "DELETE"]
615
allowed_headers = ["Content-Type", "Authorization"]
716
allow_credentials = true
17+
max_age = 86400
18+
```
819

9-
[middleware.body_limit]
10-
limit = "100KB"
20+
### Options
21+
22+
| Option | Type | Description | Default |
23+
| ------------------- | ------- | --------------------------------------------------------- | --------------------------------------------- |
24+
| `allowed_origins` | Array | List of origins that are allowed to access the resource | `["*"]` |
25+
| `allowed_methods` | Array | HTTP methods allowed | `["GET", "POST", "PUT", "DELETE", "OPTIONS"]` |
26+
| `allowed_headers` | Array | HTTP headers allowed | `["Content-Type", "Authorization"]` |
27+
| `allow_credentials` | Boolean | Indicates if cookies can be included in requests | `false` |
28+
| `max_age` | Number | How long the results of a preflight request can be cached | `86400` (24 hours) |
29+
30+
## Rate Limit
31+
32+
Limits the number of requests a client can make within a specified time period.
33+
34+
```toml
35+
# project.toml
1136

1237
[middleware.rate_limit]
13-
enabled = true
14-
max_requests = 100
15-
window = 60
38+
limit = 100
39+
window = 60 # in seconds
40+
message = "Too many requests, please try again later."
41+
```
42+
43+
### Options
44+
45+
| Option | Type | Description | Default |
46+
| --------------- | ------ | ----------------------------------------------------------------------- | --------------------- |
47+
| `limit` | Number | Maximum number of requests allowed | `100` |
48+
| `window` | Number | Time window in seconds | `60` |
49+
| `message` | String | Message to return when rate limit is exceeded | `"Too many requests"` |
50+
| `key_extractor` | String | Function to extract the rate limit key (e.g., "ip", "header:X-API-Key") | `"ip"` |
51+
52+
## Body Limit
53+
54+
Limits the size of request bodies.
55+
56+
```toml
57+
# project.toml
58+
59+
[middleware.body_limit]
60+
limit = "1mb"
61+
```
62+
63+
### Options
64+
65+
| Option | Type | Description | Default |
66+
| ------- | ------ | --------------------------------------------------- | ------- |
67+
| `limit` | String | Maximum size of request body (e.g., "1mb", "500kb") | `"1mb"` |
68+
69+
## Timeout
70+
71+
Sets a timeout for handling requests.
72+
73+
```toml
74+
# project.toml
1675

1776
[middleware.timeout]
18-
timeout = 5
77+
duration = 5000 # in milliseconds
78+
message = "Request timeout"
79+
```
80+
81+
### Options
82+
83+
| Option | Type | Description | Default |
84+
| ---------- | ------ | ------------------------------------- | ------------------- |
85+
| `duration` | Number | Timeout in milliseconds | `5000` |
86+
| `message` | String | Message to return when timeout occurs | `"Request timeout"` |
87+
88+
## Compression
89+
90+
Compresses response bodies.
1991

92+
```toml
93+
# project.toml
94+
95+
[middleware.compression]
96+
level = 6 # compression level (1-9)
97+
threshold = 1024 # minimum size to compress
2098
```
2199

22-
## CORS
100+
### Options
23101

24-
## Body limit
102+
| Option | Type | Description | Default |
103+
| ----------- | ------ | --------------------------------- | -------------------------------------------------------------------- |
104+
| `level` | Number | Compression level (1-9) | `6` |
105+
| `threshold` | Number | Minimum size in bytes to compress | `1024` |
106+
| `types` | Array | Content types to compress | `["text/plain", "text/html", "application/json", "application/xml"]` |
25107

26-
## Rate Limit
108+
## Security Headers
27109

28-
## Timeout
110+
Adds security-related HTTP headers to responses.
111+
112+
```toml
113+
# project.toml
114+
115+
[middleware.security_headers]
116+
xss_protection = "1; mode=block"
117+
content_security_policy = "default-src 'self'"
118+
```
119+
120+
### Options
121+
122+
| Option | Type | Description | Default |
123+
| ------------------------- | ------ | ------------------------------------ | ------------------------------ |
124+
| `xss_protection` | String | X-XSS-Protection header value | `"1; mode=block"` |
125+
| `content_type_options` | String | X-Content-Type-Options header value | `"nosniff"` |
126+
| `frame_options` | String | X-Frame-Options header value | `"SAMEORIGIN"` |
127+
| `content_security_policy` | String | Content-Security-Policy header value | `"default-src 'self'"` |
128+
| `referrer_policy` | String | Referrer-Policy header value | `"no-referrer-when-downgrade"` |

0 commit comments

Comments
 (0)