bruno-endpoint-creation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBruno REST API Endpoint Creation Command
Bruno REST API 端点创建指南
Expert REST API Endpoint Configuration for Bruno
专业级Bruno REST API端点配置方案
As a REST API expert, when creating Bruno endpoints, follow these proven patterns for professional API testing and documentation:
作为REST API专家,在创建Bruno端点时,请遵循以下经过验证的模式,以实现专业的API测试和文档管理:
1. Environment Configuration Best Practices
1. 环境配置最佳实践
Development Environment (Local.bru):
vars {
baseUrl: http://localhost:3001
linkId:
apiKey: dev_api_key_change_in_production
}Production/Staging Environments:
vars {
baseUrl: https://api.yourdomain.com
linkId:
}
vars:secret [
apiKey
]Key Principles:
- Use plain text variables for development (easier debugging)
- Use for sensitive data in production/staging
vars:secret - Never hardcode sensitive values in production configs
- Use descriptive variable names that match your API's naming conventions
开发环境(Local.bru):
vars {
baseUrl: http://localhost:3001
linkId:
apiKey: dev_api_key_change_in_production
}生产/预发布环境:
vars {
baseUrl: https://api.yourdomain.com
linkId:
}
vars:secret [
apiKey
]核心原则:
- 开发环境使用明文变量(便于调试)
- 生产/预发布环境使用存储敏感数据
vars:secret - 切勿在生产配置中硬编码敏感值
- 使用与API命名规范匹配的描述性变量名
2. RESTful Endpoint Structure
2. RESTful端点结构
Standard CRUD Operations Pattern:
GET /api/v1/resources # List all resources
GET /api/v1/resources/:id # Get specific resource
POST /api/v1/resources # Create new resource
PATCH /api/v1/resources/:id # Update specific resource
PUT /api/v1/resources/:id # Replace specific resource
DELETE /api/v1/resources/:id # Delete specific resource标准CRUD操作模式:
GET /api/v1/resources # List all resources
GET /api/v1/resources/:id # Get specific resource
POST /api/v1/resources # Create new resource
PATCH /api/v1/resources/:id # Update specific resource
PUT /api/v1/resources/:id # Replace specific resource
DELETE /api/v1/resources/:id # Delete specific resource3. Authentication Configuration
3. 身份验证配置
Collection-Level Authentication (Recommended):
Set authentication once at the collection level in :
collection.bruauth {
mode: bearer
}
auth:bearer {
token: {{apiKey}}
}Then inherit in all individual endpoints:
post {
url: {{baseUrl}}/api/v1/resources
body: json
auth: inherit
}Individual Endpoint Authentication (When Needed):
Only use when an endpoint needs different auth than the collection:
auth:bearer {
token: {{apiKey}}
}
auth:basic {
username: {{username}}
password: {{password}}
}
headers {
X-API-Key: {{apiKey}}
}Benefits of Collection-Level Auth:
- DRY principle - define once, use everywhere
- Easier maintenance - change auth in one place
- Cleaner endpoint files - focus on request logic
- Consistent authentication across all endpoints
集合级身份验证(推荐):
在中一次性设置集合级身份验证:
collection.bruauth {
mode: bearer
}
auth:bearer {
token: {{apiKey}}
}随后在所有独立端点中继承该配置:
post {
url: {{baseUrl}}/api/v1/resources
body: json
auth: inherit
}独立端点身份验证(按需使用):
仅当某个端点需要与集合不同的身份验证时使用:
auth:bearer {
token: {{apiKey}}
}
auth:basic {
username: {{username}}
password: {{password}}
}
headers {
X-API-Key: {{apiKey}}
}集合级身份验证的优势:
- 遵循DRY原则——一次定义,全局使用
- 维护更简便——仅需在一处修改身份验证配置
- 端点文件更简洁——专注于请求逻辑
- 所有端点的身份验证保持一致
4. Request Configuration
4. 请求配置
Standard Request Structure:
meta {
name: "Create Resource"
type: http
seq: 1
}
post {
url: {{baseUrl}}/api/v1/resources
body: json
auth: inherit
}
body:json {
{
"resource": {
"field1": "value1",
"field2": "value2"
}
}
}
params:path {
id: {{resourceId}}
}
params:query {
page: 1
limit: 20
sort: created_at
order: desc
}标准请求结构:
meta {
name: "Create Resource"
type: http
seq: 1
}
post {
url: {{baseUrl}}/api/v1/resources
body: json
auth: inherit
}
body:json {
{
"resource": {
"field1": "value1",
"field2": "value2"
}
}
}
params:path {
id: {{resourceId}}
}
params:query {
page: 1
limit: 20
sort: created_at
order: desc
}5. Response Handling & Scripts
5. 响应处理与脚本
Post-Response Scripts for Data Extraction:
Use to store values in runtime variables for use across requests in the same run:
bru.setVar()javascript
script:post-response {
// After creating a resource, store its ID in runtime variable
if (res.status === 201 && res.body && res.body.id) {
bru.setVar("resourceId", res.body.id);
bru.setVar("lastCreatedAt", res.body.created_at);
}
// After listing resources, extract the first ID for subsequent operations
if (res.status === 200 && res.body && res.body.length > 0) {
bru.setVar("resourceId", res.body[0].id);
}
}Key Difference:
- - Stores in environment variables (persists across requests, visible in Environment tab)
bru.setEnvVar() - - Stores in runtime variables (temporary, available during current collection run)
bru.setVar()
Best Practice: Use for runtime variables to avoid cluttering your environment variables with ephemeral values like extracted IDs from test runs.
bru.setVar()Pre-Request Scripts for Dynamic Data:
javascript
script:pre-request {
// Generate dynamic test data
const timestamp = Date.now();
bru.setVar("uniqueEmail", `test-${timestamp}@example.com`);
bru.setVar("randomId", Math.random().toString(36).substr(2, 9));
}用于数据提取的响应后脚本:
使用将值存储到运行时变量中,以便在同一次运行的多个请求中复用:
bru.setVar()javascript
script:post-response {
// After creating a resource, store its ID in runtime variable
if (res.status === 201 && res.body && res.body.id) {
bru.setVar("resourceId", res.body.id);
bru.setVar("lastCreatedAt", res.body.created_at);
}
// After listing resources, extract the first ID for subsequent operations
if (res.status === 200 && res.body && res.body.length > 0) {
bru.setVar("resourceId", res.body[0].id);
}
}核心区别:
- - 存储到环境变量中(跨请求持久化,可在环境标签页查看)
bru.setEnvVar() - - 存储到运行时变量中(临时存储,仅在当前集合运行期间可用)
bru.setVar()
最佳实践: 使用存储运行时变量,避免用测试运行中提取的临时ID等值占用环境变量。
bru.setVar()用于生成动态数据的请求前脚本:
javascript
script:pre-request {
// Generate dynamic test data
const timestamp = Date.now();
bru.setVar("uniqueEmail", `test-${timestamp}@example.com`);
bru.setVar("randomId", Math.random().toString(36).substr(2, 9));
}6. Error Handling & Validation
6. 错误处理与验证
Expected Status Codes:
- - Success (GET, PATCH, PUT)
200 - - Created (POST)
201 - - No Content (DELETE)
204 - - Bad Request
400 - - Unauthorized
401 - - Forbidden
403 - - Not Found
404 - - Unprocessable Entity
422 - - Internal Server Error
500
Response Validation Scripts:
javascript
script:post-response {
// Validate response structure
if (res.status === 200) {
if (!res.body || typeof res.body !== 'object') {
throw new Error('Expected JSON response body');
}
if (res.body.id && typeof res.body.id !== 'string') {
throw new Error('Expected string ID in response');
}
}
}预期状态码:
- - 请求成功(GET、PATCH、PUT)
200 - - 资源创建成功(POST)
201 - - 无返回内容(DELETE)
204 - - 请求参数错误
400 - - 未授权
401 - - 禁止访问
403 - - 资源不存在
404 - - 请求格式正确但无法处理
422 - - 服务器内部错误
500
响应验证脚本:
javascript
script:post-response {
// Validate response structure
if (res.status === 200) {
if (!res.body || typeof res.body !== 'object') {
throw new Error('Expected JSON response body');
}
if (res.body.id && typeof res.body.id !== 'string') {
throw new Error('Expected string ID in response');
}
}
}7. Documentation Standards
7. 文档规范
Comprehensive Endpoint Documentation:
docs {
Create a new resource in the system.
**Required Fields:**
- field1: Description of required field
- field2: Another required field description
**Optional Fields:**
- optional_field: Description of optional field
**Validation Rules:**
- field1 must be between 3-50 characters
- field2 must be a valid email format
**Response:**
- 201 Created: Returns the created resource with ID
- 422 Unprocessable Entity: Returns validation errors
- 401 Unauthorized: Invalid or missing authentication
**Example Usage:**
This endpoint is typically called after user authentication
to create new resources in the system.
}全面的端点文档:
docs {
Create a new resource in the system.
**Required Fields:**
- field1: Description of required field
- field2: Another required field description
**Optional Fields:**
- optional_field: Description of optional field
**Validation Rules:**
- field1 must be between 3-50 characters
- field2 must be a valid email format
**Response:**
- 201 Created: Returns the created resource with ID
- 422 Unprocessable Entity: Returns validation errors
- 401 Unauthorized: Invalid or missing authentication
**Example Usage:**
This endpoint is typically called after user authentication
to create new resources in the system.
}8. Collection Organization
8. 集合组织
Recommended Folder Structure:
Bruno Collection/
├── Environments/
│ ├── Local.bru
│ ├── Staging.bru
│ └── Production.bru
├── Authentication/
│ ├── Login.bru
│ └── Refresh Token.bru
├── Resources/
│ ├── List Resources.bru
│ ├── Get Resource.bru
│ ├── Create Resource.bru
│ ├── Update Resource.bru
│ └── Delete Resource.bru
└── Health/
└── Health Check.bru推荐的文件夹结构:
Bruno Collection/
├── Environments/
│ ├── Local.bru
│ ├── Staging.bru
│ └── Production.bru
├── Authentication/
│ ├── Login.bru
│ └── Refresh Token.bru
├── Resources/
│ ├── List Resources.bru
│ ├── Get Resource.bru
│ ├── Create Resource.bru
│ ├── Update Resource.bru
│ └── Delete Resource.bru
└── Health/
└── Health Check.bru9. Advanced Patterns
9. 高级模式
Pagination Support:
params:query {
page: 1
per_page: 20
sort: created_at
order: desc
}Filtering & Search:
params:query {
search: "search term"
status: active
created_after: "2024-01-01"
tags: "tag1,tag2"
}Bulk Operations:
body:json {
{
"resources": [
{"field1": "value1"},
{"field1": "value2"}
]
}
}分页支持:
params:query {
page: 1
per_page: 20
sort: created_at
order: desc
}过滤与搜索:
params:query {
search: "search term"
status: active
created_after: "2024-01-01"
tags: "tag1,tag2"
}批量操作:
body:json {
{
"resources": [
{"field1": "value1"},
{"field1": "value2"}
]
}
}10. Testing Strategy
10. 测试策略
Test Sequence:
- Health Check (no auth required)
- Authentication (if applicable)
- Create Resource
- List Resources
- Get Specific Resource
- Update Resource
- Delete Resource
- Error Cases (invalid data, missing auth, etc.)
Environment-Specific Testing:
- Local: Full CRUD operations with test data
- Staging: Integration testing with real data
- Production: Read-only operations and health checks
测试执行顺序:
- 健康检查(无需身份验证)
- 身份验证(如适用)
- 创建资源
- 列出资源
- 获取指定资源
- 更新资源
- 删除资源
- 异常场景测试(无效数据、缺失身份验证等)
环境专属测试策略:
- 本地环境:使用测试数据执行完整CRUD操作
- 预发布环境:使用真实数据进行集成测试
- 生产环境:仅执行只读操作和健康检查
11. Security Considerations
11. 安全注意事项
Never Include in Version Control:
- API keys
- Passwords
- Personal data
- Production secrets
Use Environment Variables:
- Store sensitive data in Bruno's secret management
- Use different credentials per environment
- Rotate secrets regularly
切勿纳入版本控制的内容:
- API密钥
- 密码
- 个人数据
- 生产环境密钥
使用环境变量:
- 将敏感数据存储在Bruno的密钥管理系统中
- 为不同环境使用不同的凭证
- 定期轮换密钥
12. Performance Testing
12. 性能测试
Load Testing Headers:
headers {
X-Load-Test: true
X-Request-ID: {{requestId}}
}Timing Validation:
javascript
script:post-response {
if (res.timings.duration > 5000) {
console.warn('Request took longer than 5 seconds');
}
}This comprehensive approach ensures your Bruno collections are professional, maintainable, and follow REST API best practices while providing excellent developer experience and thorough testing coverage.
负载测试请求头:
headers {
X-Load-Test: true
X-Request-ID: {{requestId}}
}响应时长验证:
javascript
script:post-response {
if (res.timings.duration > 5000) {
console.warn('Request took longer than 5 seconds');
}
}这种全面的方法可确保你的Bruno集合专业、易于维护,同时遵循REST API最佳实践,为开发者提供出色的使用体验,并实现全面的测试覆盖。