Response Examples

Adding response examples to your OpenAPI specification helps API consumers understand what to expect from your endpoints. This page explains how to add response examples to your Serverpod Swagger documentation.

Why Add Response Examples?

Response examples provide several benefits:

  • Help API consumers understand the expected response format
  • Serve as documentation for different response scenarios (success, error, etc.)
  • Make your API documentation more user-friendly
  • Reduce the need for trial-and-error when integrating with your API

Adding Response Examples in YAML

You can add response examples by creating a YAML file with your examples. Create a file named openapi_examples.yaml in your project root:

openapi_examples.yaml
1components:
2  examples:
3    UserSuccessResponse:
4      summary: Successful user response
5      value:
6        id: 123
7        name: "John Doe"
8        email: "john.doe@example.com"
9        createdAt: "2023-01-15T08:30:00Z"
10    
11    UserNotFoundError:
12      summary: User not found error
13      value:
14        error: "User not found"
15        code: "USER_NOT_FOUND"
16        statusCode: 404
17    
18    ValidationError:
19      summary: Validation error
20      value:
21        error: "Validation failed"
22        code: "VALIDATION_ERROR"
23        statusCode: 400
24        details:
25          - field: "email"
26            message: "Invalid email format"
27          - field: "password"
28            message: "Password must be at least 8 characters long"

The generator will include these examples in the generated OpenAPI specification.

Referencing Examples in Endpoint Annotations

You can reference your examples in endpoint annotations using the @Example annotation:

example_endpoint.dart
1/// Get user by ID
2/// 
3/// Returns a user by their ID
4('/users/:id')
5('GET')
6(response: 'UserSuccessResponse', statusCode: '200')
7(response: 'UserNotFoundError', statusCode: '404')
8Future<User> getUserById(Session session, int id);
9
10/// Create user
11/// 
12/// Creates a new user
13('/users')
14('POST')
15(response: 'UserSuccessResponse', statusCode: '201')
16(response: 'ValidationError', statusCode: '400')
17Future<User> createUser(Session session, User user);

In this example, the getUserById endpoint has examples for both successful and not found responses, and the createUser endpoint has examples for both successful and validation error responses.

Inline Examples in Annotations

For simpler cases, you can define examples directly in your annotations:

example_endpoint.dart
1/// Get user by ID
2/// 
3/// Returns a user by their ID
4('/users/:id')
5('GET')
6(response: '{"id": 123, "name": "John Doe", "email": "john.doe@example.com"}', statusCode: '200')
7(response: '{"error": "User not found", "code": "USER_NOT_FOUND", "statusCode": 404}', statusCode: '404')
8Future<User> getUserById(Session session, int id);

While this approach is convenient for simple examples, it's recommended to use the YAML file for more complex examples to keep your code clean and maintainable.

Adding Examples to Schema Definitions

You can also add examples directly to your schema definitions:

openapi_schemas.yaml
1components:
2  schemas:
3    User:
4      type: object
5      properties:
6        id:
7          type: integer
8          format: int64
9        name:
10          type: string
11        email:
12          type: string
13          format: email
14        createdAt:
15          type: string
16          format: date-time
17      required:
18        - name
19        - email
20      example:
21        id: 123
22        name: "John Doe"
23        email: "john.doe@example.com"
24        createdAt: "2023-01-15T08:30:00Z"

Multiple Examples for a Single Schema

You can define multiple examples for a single schema:

openapi_schemas.yaml
1components:
2  schemas:
3    User:
4      type: object
5      properties:
6        id:
7          type: integer
8          format: int64
9        name:
10          type: string
11        email:
12          type: string
13          format: email
14        role:
15          type: string
16          enum: [admin, user, guest]
17      required:
18        - name
19        - email
20      examples:
21        admin:
22          summary: Admin user example
23          value:
24            id: 1
25            name: "Admin User"
26            email: "admin@example.com"
27            role: "admin"
28        regularUser:
29          summary: Regular user example
30          value:
31            id: 123
32            name: "John Doe"
33            email: "john.doe@example.com"
34            role: "user"
35        guestUser:
36          summary: Guest user example
37          value:
38            id: 456
39            name: "Guest User"
40            email: "guest@example.com"
41            role: "guest"

Examples for Different Response Codes

You can define examples for different response codes in your YAML file:

openapi_paths.yaml
1paths:
2  /users/{id}:
3    get:
4      responses:
5        '200':
6          description: Successful operation
7          content:
8            application/json:
9              schema:
10                $ref: '#/components/schemas/User'
11              examples:
12                userExample:
13                  $ref: '#/components/examples/UserSuccessResponse'
14        '404':
15          description: User not found
16          content:
17            application/json:
18              schema:
19                $ref: '#/components/schemas/Error'
20              examples:
21                notFoundExample:
22                  $ref: '#/components/examples/UserNotFoundError'

Note: The paths section in the YAML file is more advanced and might override the automatically generated paths. Use this approach with caution and only when you need fine-grained control over your API documentation.

Combining Examples with Custom Schemas

You can combine examples with custom schemas in a single YAML file:

openapi_custom.yaml
1components:
2  schemas:
3    ApiResponse:
4      type: object
5      properties:
6        data:
7          type: object
8          nullable: true
9        error:
10          type: object
11          nullable: true
12          properties:
13            code:
14              type: string
15            message:
16              type: string
17        success:
18          type: boolean
19      required:
20        - success
21  
22  examples:
23    SuccessResponse:
24      summary: Successful response
25      value:
26        data:
27          id: 123
28          name: "John Doe"
29        error: null
30        success: true
31    
32    ErrorResponse:
33      summary: Error response
34      value:
35        data: null
36        error:
37          code: "INTERNAL_ERROR"
38          message: "An unexpected error occurred"
39        success: false

Next Steps