一键导入
layer-06-api
Expert knowledge for API Layer modeling in Documentation Robotics
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Expert knowledge for API Layer modeling in Documentation Robotics
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Expert knowledge for Data Store Layer modeling in Documentation Robotics
Graph-based code intelligence for using dr analyzer subcommands to understand codebase structure, discover elements, and verify model alignment
Expert knowledge for Application Layer modeling in Documentation Robotics
Expert knowledge for Motivation Layer modeling in Documentation Robotics
Expert knowledge for Business Layer modeling in Documentation Robotics
Expert knowledge for Security Layer modeling in Documentation Robotics
| name | LAYER_06_API |
| description | Expert knowledge for API Layer modeling in Documentation Robotics |
| triggers | ["OpenAPI","REST API","endpoint","operation","swagger","API specification","HTTP method","request","response"] |
| version | 0.7.0 |
Layer Number: 06 Specification: Metadata Model Spec v0.7.0 Purpose: Defines REST API contracts using OpenAPI 3.0, specifying endpoints, operations, request/response schemas, and security requirements.
The API Layer captures API contracts:
This layer uses OpenAPI 3.0.3 (de facto industry standard) with custom extensions for cross-layer traceability.
Central Entity: The Operation (HTTP method on a path) is the core modeling unit.
| Entity Type | Description |
|---|---|
| OpenAPIDocument | Root of an OpenAPI specification file (version 3.0.3) |
| Info | Metadata about the API (title, description, version, contact, license) |
| Server | Server where the API is available (with URL and variables) |
| Paths | Available API endpoints and operations |
| PathItem | Operations available on a path |
| Operation | Single API operation (HTTP method on a path) - CENTRAL ENTITY |
| Parameter | Parameter for an operation (locations: query, header, path, cookie) |
| RequestBody | Request payload for an operation |
| Responses | Possible responses from an operation |
| Response | Single response definition with status code |
| MediaType | Media type and schema for request/response body |
| Components | Reusable component definitions (schemas, responses, parameters, examples, security schemes) |
| Schema | Data type definition (JSON Schema subset) |
| Entity Type | Description |
|---|---|
| Tag | Metadata label for grouping operations |
| ExternalDocumentation | Reference to external documentation |
| Contact | Contact information for API owner |
| License | Legal license for API |
| ServerVariable | Variable placeholder in server URL templates |
| Header | HTTP header parameters for requests/responses |
| Link | Relationship between API responses and subsequent operations (HATEOAS) |
| Callback | Webhook or callback URL pattern |
| Example | Sample values for documentation and testing |
| Encoding | Serialization details for multipart content |
| SecurityScheme | Security mechanism (types: apiKey, http, oauth2, openIdConnect) |
| Entity Type | Description |
|---|---|
| OAuthFlows | Configuration for OAuth 2.0 flows |
| Condition | Logical expression for policy evaluation |
| RetentionPolicy | Data retention policies |
| ValidationRule | Data validation constraints |
| Source | Predicate | Target | Example |
|---|---|---|---|
| OpenAPIDocument | composes | Info | Document has metadata |
| OpenAPIDocument | composes | Paths | Document defines endpoints |
| OpenAPIDocument | composes | Components | Document has reusable components |
| Paths | composes | PathItem | Paths contain path items |
| PathItem | composes | Operation | Path has HTTP methods |
| PathItem | composes | Parameter | Path-level parameters |
| Operation | composes | Parameter | Operation-specific parameters |
| Operation | composes | RequestBody | Request payload definition |
| Operation | composes | Responses | Response definitions |
| Responses | composes | Response | Individual status responses |
| RequestBody | composes | MediaType | Request content types |
| Response | composes | MediaType | Response content types |
| Response | composes | Header | Response headers |
| Response | composes | Link | HATEOAS links |
| MediaType | composes | Schema | Data structure |
| MediaType | composes | Example | Sample data |
| MediaType | composes | Encoding | Serialization details |
| Components | composes | Schema | Reusable schemas |
| Components | composes | Response | Reusable responses |
| Components | composes | Parameter | Reusable parameters |
| Components | composes | Example | Reusable examples |
| Components | composes | RequestBody | Reusable request bodies |
| Components | composes | Header | Reusable headers |
| Components | composes | SecurityScheme | Security definitions |
| Components | composes | Link | Reusable links |
| Components | composes | Callback | Reusable callbacks |
| Info | composes | Contact | API owner contact |
| Info | composes | License | API license |
| SecurityScheme | composes | OAuthFlows | OAuth2 configuration |
| Source | Predicate | Target | Example |
|---|---|---|---|
| OpenAPIDocument | aggregates | Server | API deployment servers |
| OpenAPIDocument | aggregates | Tag | Operation tags |
| OpenAPIDocument | aggregates | SecurityRequirement | Global security |
| Server | aggregates | ServerVariable | URL template variables |
| PathItem | aggregates | Parameter | Shared parameters |
| Operation | aggregates | Callback | Webhooks |
| Operation | aggregates | SecurityRequirement | Operation-level security |
| Source | Predicate | Target | Example |
|---|---|---|---|
| Schema | references | Schema | Schema $ref to another schema |
| Parameter | references | Schema | Parameter uses schema |
| Header | references | Schema | Header uses schema |
| Link | references | Operation | Link points to operation (operationId) |
| Callback | references | PathItem | Callback references path definition |
| Operation | references | Tag | Operation tagged for grouping |
| Tag | references | ExternalDocumentation | Tag links to external docs |
| OpenAPIDocument | references | ExternalDocumentation | Document links to external docs |
| Encoding | references | Header | Encoding uses headers |
| Source | Predicate | Target | Example |
|---|---|---|---|
| Schema | specializes | Schema | Schema inheritance (allOf, oneOf, anyOf) |
| Source | Predicate | Target | Example |
|---|---|---|---|
| Operation | triggers | Callback | Operation invokes webhook |
| SecurityScheme | serves | Operation | Security scheme protects operation |
| Source | Predicate | Target | Example |
|---|---|---|---|
| Contact | associated-with | OpenAPIDocument | Contact info for API |
| License | associated-with | OpenAPIDocument | Legal license |
OpenAPI specification includes custom extensions (x-* properties) for cross-layer traceability:
Cross-layer links to Business and Application layers use dr relationship add:
dr relationship add api.<type>.<name> business.<type>.<name> --predicate realizes
dr relationship add api.<type>.<name> application.<type>.<name> --predicate realizes
Use dr catalog types to list all valid predicates.
OpenAPI x-* properties (set via --properties) are used for same-element metadata:
| Target Layer | Extension Property | Example |
|---|---|---|
| Layer 1 (Motivation) | x-supports-goals | Operation supports business goals |
| Layer 1 (Motivation) | x-fulfills-requirements | Operation fulfills functional requirements |
| Layer 1 (Motivation) | x-governed-by-principles | Operation follows architectural principles |
| Layer 1 (Motivation) | x-constrained-by | Operation subject to constraints (GDPR, HIPAA, SOX) |
| Layer 7 (Data Model) | schema.$ref | Schema references JSON Schema definition |
| Layer 3 (Security) | x-security-resource | Operation protected by SecureResource |
| Layer 3 (Security) | x-required-permissions | Operation requires specific permissions |
| Layer 3 (Security) | x-rate-limit | Rate limiting configuration |
| Layer 11 (APM) | x-apm-business-metrics | Operation tracked by business metrics |
| Layer 11 (APM) | x-apm-sla-target-latency | Expected response time (e.g., "100ms") |
| Layer 11 (APM) | x-apm-sla-target-availability | Expected availability (e.g., "99.9%") |
| Layer 11 (APM) | x-apm-trace | Distributed tracing enabled |
| Layer 11 (APM) | x-apm-criticality | Business criticality (critical, high, medium, low) |
Lower layers reference API layer to show implementation and data structure.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(
title="User Management API", # OpenAPIDocument: Info.title
description="API for managing user accounts", # Info.description
version="1.0.0" # Info.version
)
class UserCreateRequest(BaseModel): # Schema (RequestBody)
username: str
email: str
full_name: str
class UserResponse(BaseModel): # Schema (Response)
user_id: str
username: str
email: str
created_at: datetime
@app.post(
"/api/users", # PathItem + Operation (POST)
response_model=UserResponse, # Response schema
status_code=201, # Response status
tags=["Users"], # Tag
summary="Create a new user", # Operation.summary
description="Creates a new user account with the provided details" # Operation.description
)
async def create_user(user: UserCreateRequest) -> UserResponse: # RequestBody + Response
"""
x-apm-sla-target-latency: 200ms
x-required-permissions: users.write
"""
pass
Maps to:
import express from "express";
import { body, param, query, validationResult } from "express-validator";
const router = express.Router();
/**
* @openapi
* /api/orders/{orderId}:
* get:
* summary: Get order by ID
* description: Retrieves a single order by its unique identifier
* tags:
* - Orders
* parameters:
* - name: orderId
* in: path
* required: true
* schema:
* type: string
* format: uuid
* responses:
* 200:
* description: Order found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Order'
* 404:
* description: Order not found
* x-apm-sla-target-latency: 100ms
* x-apm-criticality: high
*/
router.get(
"/api/orders/:orderId",
param("orderId").isUUID(),
async (req, res) => {
// Implementation
}
);
Maps to:
@RestController
@RequestMapping("/api/products")
@Tag(name = "Products", description = "Product management operations")
public class ProductController {
@Operation(
summary = "List products",
description = "Returns a paginated list of products",
extensions = {
@Extension(name = "x-apm-sla-target-latency", properties = @ExtensionProperty(name = "latency", value = "150ms")),
@Extension(name = "x-required-permissions", properties = @ExtensionProperty(name = "permissions", value = "products.read"))
}
)
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "Products retrieved successfully",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ProductListResponse.class)
)
)
})
@GetMapping
public ResponseEntity<ProductListResponse> listProducts(
@Parameter(description = "Page number", example = "1") @RequestParam(defaultValue = "1") int page,
@Parameter(description = "Page size", example = "20") @RequestParam(defaultValue = "20") int size
) {
// Implementation
}
}
Maps to:
openapi: 3.0.3
info:
title: Payment Processing API
description: API for processing customer payments
version: 2.1.0
contact:
name: API Support
email: api-support@example.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
x-governed-by-principles:
- motivation/principle/api-first-design
- motivation/principle/security-by-design
servers:
- url: https://api.example.com/v2
description: Production server
- url: https://staging-api.example.com/v2
description: Staging server
paths:
/payments:
post:
summary: Process payment
description: Processes a payment transaction
operationId: processPayment
tags:
- Payments
security:
- oauth2: [payments.write]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/PaymentRequest"
examples:
credit-card:
$ref: "#/components/examples/CreditCardPayment"
responses:
"201":
description: Payment processed successfully
content:
application/json:
schema:
$ref: "#/components/schemas/PaymentResponse"
"400":
$ref: "#/components/responses/BadRequest"
"401":
$ref: "#/components/responses/Unauthorized"
x-apm-sla-target-latency: 500ms
x-apm-sla-target-availability: 99.99%
x-apm-criticality: critical
x-required-permissions:
- payments.write
x-rate-limit:
requests: 100
window: 60s
components:
schemas:
PaymentRequest:
type: object
required:
- amount
- currency
- payment_method
properties:
amount:
type: number
format: double
minimum: 0.01
example: 99.99
currency:
type: string
enum: [USD, EUR, GBP]
example: USD
payment_method:
$ref: "#/components/schemas/PaymentMethod"
PaymentResponse:
type: object
properties:
transaction_id:
type: string
format: uuid
status:
type: string
enum: [pending, completed, failed]
timestamp:
type: string
format: date-time
securitySchemes:
oauth2:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://auth.example.com/oauth/authorize
tokenUrl: https://auth.example.com/oauth/token
scopes:
payments.read: Read payment information
payments.write: Process payments
responses:
BadRequest:
description: Invalid request
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
examples:
CreditCardPayment:
value:
amount: 99.99
currency: USD
payment_method:
type: credit_card
card_number: "4111111111111111"
# Create the API specification document
dr add api document "payment-api" \
--properties version=3.0.3,title="Payment Processing API",api-version=2.1.0 \
--description "API for processing customer payments"
# Add API metadata
dr add api info "payment-api-info" \
--properties title="Payment Processing API",version=2.1.0,contact-email=api@example.com \
--description "API metadata and contact information"
# Link to motivation layer
dr relationship add "api/document/payment-api" \
governed-by "motivation/principle/api-first-design"
# Production server
dr add api server "production-server" \
--properties url=https://api.example.com/v2,description="Production server" \
--description "Production API server"
# Staging server
dr add api server "staging-server" \
--properties url=https://staging-api.example.com/v2,description="Staging server" \
--description "Staging API server"
# OAuth2 security
dr add api security-scheme "oauth2-auth" \
--properties type=oauth2,flow=authorizationCode,authorization-url=https://auth.example.com/oauth/authorize,token-url=https://auth.example.com/oauth/token \
--description "OAuth2 authorization code flow"
# API Key security
dr add api security-scheme "api-key-auth" \
--properties type=apiKey,in=header,name=X-API-Key \
--description "API key authentication"
# Request schema
dr add api schema "payment-request" \
--properties type=object,required=amount:currency:payment_method \
--description "Payment request payload"
# Response schema
dr add api schema "payment-response" \
--properties type=object \
--description "Payment processing response"
# Link to data model layer
dr relationship add "api/schema/payment-request" \
references "data-model/schema/payment-request"
# POST operation
dr add api operation "process-payment" \
--properties path=/payments,method=POST,operation-id=processPayment \
--description "Processes a payment transaction"
# Add APM and security extensions
dr add api operation "process-payment" \
--properties x-apm-sla-target-latency=500ms,x-apm-sla-target-availability=99.99%,x-apm-criticality=critical,x-required-permissions=payments.write
# Link to business layer via relationship
dr relationship add api.operation.process-payment business.service.payment-processing --predicate realizes
# GET operation
dr add api operation "get-payment" \
--properties path=/payments/{paymentId},method=GET,operation-id=getPayment \
--description "Retrieves payment details by ID"
# Path parameter
dr add api parameter "payment-id-param" \
--properties name=paymentId,in=path,required=true,type=string,format=uuid \
--description "Payment transaction ID"
# Query parameter
dr add api parameter "status-filter" \
--properties name=status,in=query,required=false,type=string,enum=pending:completed:failed \
--description "Filter payments by status"
# Link parameter to operation
dr relationship add "api/operation/get-payment" \
has-parameter "api/parameter/payment-id-param"
# Request body
dr add api request-body "payment-request-body" \
--properties required=true,content-type=application/json \
--description "Payment request payload"
# Link request body to schema
dr relationship add "api/request-body/payment-request-body" \
uses-schema "api/schema/payment-request"
# Response
dr add api response "payment-success-response" \
--properties status-code=201,description="Payment processed successfully" \
--description "Successful payment response"
# Link response to schema
dr relationship add "api/response/payment-success-response" \
uses-schema "api/schema/payment-response"
# Add tags
dr add api tag "payments" \
--properties name=Payments \
--description "Payment processing operations"
dr add api tag "refunds" \
--properties name=Refunds \
--description "Refund operations"
# Tag operations
dr relationship add "api/operation/process-payment" \
tagged-with "api/tag/payments"
# Link to business layer
dr relationship add "api/operation/process-payment" \
realizes "business/service/payment-processing"
# Link to application layer
dr relationship add "api/document/payment-api" \
realizes "application/service/payment-api"
# Link to security layer
dr relationship add "api/operation/process-payment" \
protected-by "security/secure-resource/payment-api"
# Link to motivation layer
dr relationship add "api/operation/process-payment" \
supports "motivation/goal/reduce-checkout-time"
# Link to APM layer
dr relationship add "api/operation/process-payment" \
tracked-by "apm/metric/payment-processing-latency"
# Validate API layer
dr validate --layer api
# Export to OpenAPI YAML
dr export openapi --output payment-api.yaml
# Validate exported OpenAPI with external tools
spectral lint payment-api.yaml
Different operations have different SLA targets:
# Search operation: fast response
x-apm-sla-target-latency: "50ms"
x-apm-sla-target-availability: "99.9%"
x-apm-criticality: "high"
# Write operation: moderate latency
x-apm-sla-target-latency: "200ms"
x-apm-sla-target-availability: "99.95%"
x-apm-criticality: "critical"
# Batch operation: longer latency acceptable
x-apm-sla-target-latency: "10s"
x-apm-sla-target-availability: "99.5%"
x-apm-criticality: "medium"
# Reporting: can be slower
x-apm-sla-target-latency: "5s"
x-apm-sla-target-availability: "99%"
x-apm-criticality: "low"
dr relationship add to link API operations to business services for traceability| Issue | Cause | Fix |
|---|---|---|
| Missing Operations | Paths defined but no operations | Add HTTP methods (GET, POST, etc.) |
| Unlinked Schemas | Schemas not referenced by operations | Link schemas to request/response bodies |
| Missing Security | Operations lack security requirements | Add securitySchemes and apply to operations |
| No Cross-Layer Links | API not linked to business/application | Run dr relationship add <api-element> <target-element> --predicate realizes |
| Missing SLA Targets | Operations lack performance targets | Add x-apm-sla-target-* extensions |
| Untagged Operations | Operations not organized by tags | Add tags for grouping |
| No Examples | Schemas lack examples | Add example values for documentation |
| Invalid OpenAPI | Spec doesn't validate | Use Spectral or openapi-validator |
Add Commands:
dr add api document <name> --properties version=3.0.3,title=<title>
dr add api operation <name> --properties path=<path>,method=<method>
dr add api schema <name> --properties type=<type>
dr add api parameter <name> --properties name=<name>,in=<location>
dr add api security-scheme <name> --properties type=<type>
dr add api tag <name> --properties name=<display-name>
Relationship Commands:
dr relationship add <operation> uses-schema <schema>
dr relationship add <operation> has-parameter <parameter>
dr relationship add <operation> tagged-with <tag>
dr relationship add <schema> references <schema>
Cross-Layer Commands:
dr relationship add api/<operation> realizes business/<service>
dr relationship add api/<document> realizes application/<service>
dr relationship add api/<schema> references data-model/<schema>
dr relationship add api/<operation> protected-by security/<resource>
dr relationship add api/<operation> supports motivation/<goal>
Export Commands:
dr export openapi --output api-spec.yaml
dr export openapi --layer api --format json --output api-spec.json
Validation Commands:
dr validate --layer api
spectral lint api-spec.yaml
swagger-cli validate api-spec.yaml
Documentation Robotics defines custom OpenAPI extensions for cross-layer traceability:
# Motivation Layer Links
x-supports-goals: [motivation/goal/id1, motivation/goal/id2]
x-fulfills-requirements: [motivation/requirement/id1]
x-governed-by-principles: [motivation/principle/id1]
x-constrained-by: [motivation/constraint/id1]
# Business and Application Layer Links — use dr relationship add (not x-* properties)
# dr relationship add api.<type>.<name> business.<type>.<name> --predicate realizes
# dr relationship add api.<type>.<name> application.<type>.<name> --predicate realizes
# Security Layer Links
x-security-resource: security/secure-resource/id
x-required-permissions: [users.read, users.write]
x-rate-limit:
requests: 100
window: 60s
# APM Layer Links
x-apm-business-metrics: [apm/metric/id1]
x-apm-sla-target-latency: "100ms"
x-apm-sla-target-availability: "99.9%"
x-apm-trace: true
x-apm-criticality: "high" # critical, high, medium, low
These extensions enable full traceability from API operations to business goals, requirements, security controls, and monitoring metrics.
The API Layer is the contract layer - it defines HOW external consumers interact with your system. Every operation should:
Use OpenAPI 3.0.3 as the foundation, leverage auto-generation tools from your framework, and extend with custom properties for full cross-layer integration.