如何在JSON Schema及Open API(OAS)中定义REST API的UUID属性?
Great question! When working on REST API documentation with JSON Schema and OpenAPI Specification (OAS), defining UUID properties correctly is crucial for avoiding ambiguity and ensuring your API contract is clear and actionable. Let’s break down the best practices for both standards:
JSON Schema provides a straightforward way to mark string properties as UUIDs using the format keyword, which is widely recognized by validation tools and documentation generators.
Basic UUID Definition
The simplest and most standard approach is to set type: string alongside format: uuid:
{ "type": "object", "properties": { "order_id": { "type": "string", "format": "uuid", "description": "Unique identifier for the order, following UUID v4 format" } }, "required": ["order_id"] }
This tells tools that the string should conform to UUID formatting rules (e.g., 550e8400-e29b-41d4-a716-446655440000).
Strict Regex Validation (Optional)
If you need even tighter control over the UUID pattern (e.g., enforcing UUID v4 specifically), you can add a pattern keyword with a regex that matches the exact UUID structure:
{ "type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", "description": "Strict validation for UUID v4 (enforces the version 4 identifier)" }
OAS builds on JSON Schema, so the core UUID definition is nearly identical—but there are context-specific ways to apply it in paths, parameters, and request/response bodies.
UUID as a Path Parameter
When defining UUIDs in path parameters, embed the schema directly in the parameter definition:
paths: /orders/{orderId}: get: summary: Retrieve an order by UUID parameters: - name: orderId in: path required: true schema: type: string format: uuid description: UUID of the order to fetch
UUID in Request/Response Bodies
For request or response payloads, define the UUID property within the schema of the body content:
paths: /orders: post: summary: Create a new order requestBody: content: application/json: schema: type: object properties: id: type: string format: uuid description: Optional UUID for the order (if omitted, the server will generate one) customer_name: type: string required: ["customer_name"] responses: 201: description: Order created successfully content: application/json: schema: type: object properties: id: type: string format: uuid customer_name: type: string
Most OAS tools (like Swagger UI or Redoc) will automatically recognize the uuid format and generate realistic example values, making your docs more user-friendly.
Just like in JSON Schema, you can add a pattern keyword here if you need stricter validation for specific UUID versions.
内容的提问来源于stack exchange,提问作者Slava Fomin II

