Cách tạo nhiều examples cho swagger (openapi) và config @stoplight/prism-cli trả về đúng example mong muốn 🦥

Tóm tắt:

  1. Thêm nhiều examples theo hướng dẫn ở swagger docs@stoplight/prism-cli - response-examples.
  2. response-examples.
  3. Dùng modheader để custom header request gửi lên từ trình duyệt. Ví dụ call URL với Prefer header example=dog.
  4. Nhận về đúng example mà mình đã mô tả trong modheader.

🧱 Cài đặt @stoplight/prism-cli

Use this tool for HTTP mock server simulates.

npm install -g @stoplight/prism-cli
prism mock ./media/api_docs/swagger.yaml

📓 swagger editor

Với vscode thì sử dụng extention swagger-viewer giúp mình tiện view swagger hay validte source-code của swagger.

🎶 Thêm examples cho swagger

Tạo 1 thuộc tính examples đồng cấp với schema. Điều khác biệt với chỉ 1 example là:

  • example là 1 thuộc tính của schema.
  • examples có 1 hoặc nhiều thuộc tính đại diện cho tên của 1 example, mỗi thuộc tính đó (tên example) có thuộc tính là value, trong thuộc tính value mới mô tả nội dung example.

Bên trong examples sẽ có các example - phân biệt bằng tên riêng của từng example:

examples: # Multiple examples
  zero: # Distinct name
    value: 0 # Example value
    summary: A sample limit value # Optional description
  max: # Distinct name
    value: 50 # Example value
    summary: A sample limit value # Optional description
  short-list: # Distinct name
    value: 25 # Example value
    summary: A sample limit value # Optional description

🌧 Set header để controll response nào được trả về

Dùng browser extention - modheader

Ví dụ set Prefer header example=short-list, với short-list là example đã được định nghĩa trong file swagger.

modheader

Dùng API testing client để kiểm thử xem có đúng kết quả trả về theo như example đã định nghĩa hay không

Ví dụ dùng vscode extention - thunder-client:

Screenshot from 2021-06-02 11-28-25.png

Hay dùng Open source API development tool - 1 API client - hoppscotch.io để xác nhận lại response.