API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Designing APIs
  • Introduction
  • Table of Contents
  • API Academy
    • Get Started
      • What is an API?
      • How Does an API Work?
      • How to Call an API?
      • How to Read an API Documentation?
      • Chapter Summary
      • Get realtime weather
    • API Fundamentals
      • API Funtamentals: Overview
      • Method & Path
      • Parameters
      • Request Body
      • Responses
      • API Specification & OAS
      • Chapter Summary
    • Working with APIs
      • Working with APIs: Overview
      • Making Requests from Spec
      • Environments and Variables
      • Chaining Multiple Endpoints
      • Handling Authentication
      • Handling API Signatures
      • Introduction to Scripts
      • Chapter Summary
    • Mocking APIs
      • Mocking APIs: Overview
      • Smart Mock
      • Mock Expectations
      • Cloud Mock
      • Mock Scripts
      • Chapter Summary
    • Designing APIs
      • Designing APIs: Overview
      • Introduction to API Design
      • Creating Your First API Project
      • Analyzing Requirements and Planning Your API
      • Designing Data Models
      • Designing Endpoints
      • Using Components and Reusability
      • Setting Up Authentication
      • API Design Guidelines
      • Chapter Summary
    • Developing APIs
      • Developing APIs: Overview
      • Setup: Install Your AI Coding Assistant
      • Quick Start: From Spec to Running API in 30 Minutes
      • Understanding the Generated Code
      • Testing Your API with Apidog
      • Deployment: Put Your API Online
      • Chapter Summary
    • Testing APIs
      • Testing APIs: Overview
      • Getting Started: Your First Test Scenario
      • Integration Testing and Data Passing
      • Dynamic Values
      • Assertions and Validations
      • Flow Control: If, For, ForEach
      • Data-Driven Testing
      • Performance Testing
      • Test Reports and Analysis
      • CI/CD Integration
      • Scheduled Tasks and Automation
      • Advanced Testing Strategies
      • Chapter Summary
    • API Documentations
      • API Documentations: Overview
      • Publishing Your First API Doc
      • Customizing Documentation Appearance
      • Interactive Features for Consumers
      • Advanced Publishing Settings
      • Managing API Versions
      • Chapter Summary
    • Advanced API Technologies
      • API Technologies: Overview
      • GraphQL
      • gRPC
      • WebSocket
      • Socket.IO
      • Server-Sent Events (SSE)
      • SOAP
      • Chapter Summary
    • API Lifecycle
      • API Lifecycle: Overview
      • Stages of the API Lifecycle
      • API Governance
      • API Security Best Practices
      • Monitoring and Analytics
      • API Versioning Strategies
      • The Future of APIs
      • Chapter Summary
    • API Security
      • API Security: Overview
      • API Security Fundamentals
      • Authentication vs Authorization
      • Understanding OAuth 2.0 and OpenID Connect
      • JSON Web Tokens (JWT)
      • OWASP API Security Top 10
      • Encryption and HTTPS
      • Chapter Summary
    • API Tools
      • API Tools: Overview
      • The Evolution of API Tools
      • API Clients
      • Command Line Tools (cURL, HTTPie)
      • API Design and Documentation Tools
      • API Mocking Tools
      • API Testing Tools
      • All-in-One API Platforms
      • Chapter Summary
    • API Gateway
      • API Gateway: Overview
      • What is an API Gateway?
      • Key Features of API Gateways
      • API Gateway vs Load Balancer vs Service Mesh
      • Popular API Gateway Solutions
      • The BFF (Backend for Frontend) Pattern
      • Chapter Summary
  • Modern Pet Store
    • Pet
      • Get Pet
      • Update Pet
      • Delete Pet
      • Create Pet
      • List Pets
      • Upload Pet Image
    • User
      • Update User
      • Get User
      • Delete User
      • Login
      • Logout
      • Create User
    • Store
      • List Inventory
      • Create Order
      • Get Order
      • Delete Order
      • Callback Example
      • Pay for an Order
    • Payments
      • Pay Order
    • Chat
      • Create Chat Completion
    • Webhooks
      • Pet Adopted Event
      • New Pet Available Event
  • Schemas
    • Pet
    • Category
    • User
    • ApiResponse
    • OrderPayment
    • Tag
    • Order
    • Links-Order
    • PetCollection
    • Bank Card
    • Bank Account
    • Links
    • Error
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Designing APIs

Using Components and Reusability

You've now designed schemas and created endpoints for the User module. But as your API grows, you'll find yourself repeating the same elements across endpointsβ€”error responses, pagination parameters, common headers, and more.
This is where components come in. Components allow you to define reusable elements once and reference them across multiple endpoints, making your API design more consistent, maintainable, and efficient.
In this article, we'll learn how to use Apidog's component features to improve the User module design with reusable error responses and default templates.

1. What Are Components?#

Components are reusable building blocks for your API design. Instead of defining the same error response or security scheme in every endpoint, you define it once as a component and reference it wherever needed.

Why Use Components?#

1.
Consistency β€” All endpoints use the same structure for common elements
2.
Efficiency β€” Define once, use many times (DRY principle)
3.
Maintainability β€” Update in one place, changes apply everywhere
4.
OpenAPI Compliance β€” Components align with OpenAPI specification standards

What Can Be Reusable Components?#

In Apidog, you can create reusable components for:
Schemas β€” Data models (already covered in the previous article)
Responses β€” Common error responses (400, 404, 500, etc.)
Security Schemes β€” Authentication methods (will be covered in the next article)

2. Creating Response Components#

The most common use case for components is error responses. Errors like 400 Bad Request, 404 Not Found, and 500 Internal Server Error typically have the same structure across all endpoints.
Let's create reusable error response components for the User module.

Step 1: Design Error Response Structure#

First, let's design what our error responses should look like. A good error response includes:
{
  "type": "https://api.example.com/errors/not-found",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "The requested user with ID 'usr_invalid' was not found",
  "instance": "/users/usr_invalid"
}
This follows RFC 9457 (Problem Details for HTTP APIs), a standard for API error responses.

Step 2: Create Error Schema#

Before creating response components, let's create an Error schema:
1.
Go to Schemas β†’ Click βž• β†’ New Schema
2.
Name it "Error"
3.
Description: "Standard error response following RFC 9457"
4.
Click "Generate from JSON etc." and paste:
{
  "type": "https://api.example.com/errors/validation-error",
  "title": "Validation Error",
  "status": 422,
  "detail": "The request contains invalid data",
  "instance": "/users"
}
5.
Refine the schema:
Mark type, title, status as required
detail and instance are optional
Set status type to integer
Add descriptions for each field

Step 3: Create Response Components#

Now let's create response components:
1.
In the left sidebar, navigate to Components β†’ Responses
2.
Click "New Response" to create a new response component
Create 400 Bad Request Component:
1.
Name: "Bad Request"
2.
HTTP Status Code: 400
3.
Content Type: application/json
4.
Schema: Select "Error" schema
5.
Add an example:
{
  "type": "https://api.example.com/errors/bad-request",
  "title": "Bad Request",
  "status": 400,
  "detail": "Invalid input parameters",
  "instance": "/users"
}
6.
Added in new endpoints by default: Select "Yes" if you want this automatically added to all new endpoints
Create 404 Not Found Component:
1.
Name: "Not Found"
2.
HTTP Status Code: 404
3.
Content Type: application/json
4.
Schema: Select "Error" schema
5.
Add an example:
{
  "type": "https://api.example.com/errors/not-found",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "The requested resource was not found",
  "instance": "/users/usr_invalid"
}
Create 422 Validation Error Component:
1.
Name: "Validation Error"
2.
HTTP Status Code: 422
3.
Content Type: application/json
4.
Schema: Select "Error" schema (or create an extended version with an errors array)
5.
Add an example:
{
  "type": "https://api.example.com/errors/validation-error",
  "title": "Validation Error",
  "status": 422,
  "detail": "Request validation failed",
  "instance": "/users",
  "errors": [
    {
      "field": "email",
      "message": "Email format is invalid"
    }
  ]
}

Step 4: Reference Components in Endpoints#

Now let's add these error responses to our User endpoints:
1.
Open the POST /users endpoint
2.
Go to the Response tab
3.
Click "Add Response" β†’ Select "From Component"
4.
Choose "Bad Request (400)" from the list
5.
Repeat for "Validation Error (422)"
The response components are now referenced in your endpoint. They appear with a component icon and cannot be edited directly in the endpoint.
Benefits:
If you update the component (e.g., add a new field), all endpoints automatically get the update
Consistency across all endpoints is guaranteed

Step 5: Bulk Add Components#

Instead of adding components one by one to each endpoint, use bulk operations:
1.
Go to Components β†’ Responses
2.
Select a response component (e.g., "404 Not Found")
3.
Click the "..." menu β†’ "Batch add to endpoints"
4.
Select which endpoints should include this response:
GET /users/{id}
PUT /users/{id}
DELETE /users/{id}
5.
Click "Confirm"
Now the 404 response is added to all selected endpoints at once.

3. Default Response Template#

Many organizations have a standardized response structure. For example, all successful responses might follow this pattern:
{
  "success": true,
  "data": { /* actual data here */ },
  "timestamp": "2024-01-15T10:30:00Z"
}
Apidog's Default Response Template lets you set this as the starting point for all new endpoints.

Configure Default Response Template#

1.
Go to Components β†’ Default Response Template
2.
Edit the template:
Status Code: 200
Content Type: application/json
Schema: Define your standard wrapper structure
3.
Every new endpoint will now start with this response structure
Important: Changes to the default template only affect new endpoints. Existing endpoints remain unchanged.

4. Component Management Best Practices#

Updating Components#

When you update a component:
1.
Go to Components β†’ select the component
2.
Make your changes
3.
All endpoints referencing this component are automatically updated
Use case: If you need to add a new field to all error responses (e.g., requestId), update the Error schema once, and it applies everywhere.

Dereferencing Components#

Sometimes you need to customize a component for a specific endpoint:
1.
In the endpoint, hover over the referenced component
2.
Click "Dereference"
3.
The component becomes a regular response that you can edit
4.
Changes to the original component will no longer affect this endpoint
When to dereference:
The endpoint needs a slightly different error structure
You want to customize one specific case without affecting others

Versioning Considerations#

When your API evolves:
Minor changes (adding optional fields): Update components directly
Breaking changes (removing fields, changing types): Create new components with version suffixes (e.g., ErrorV2)

5. Practical Exercise: Add Components to User Module#

Let's apply what we've learned to the User module endpoints:

Task 1: Add Error Response Components#

1.
Add 400 Bad Request to all endpoints that accept input:
POST /users
PUT /users/{id}
POST /user/login
2.
Add 404 Not Found to endpoints that fetch specific resources:
GET /users/{id}
PUT /users/{id}
DELETE /users/{id}
3.
Add 422 Validation Error to endpoints with complex validation:
POST /users
PUT /users/{id}
Use bulk operations to save time!

Task 2: Verify Consistency#

Check that all your endpoints now have:
Consistent error response structures
All error responses reference the same Error schema
Each error response includes appropriate examples

6. Key Takeaways#

Using components and reusability features in Apidog helps you:
1.
Response Components β€” Define error responses once, reuse everywhere
2.
Bulk Operations β€” Add components to multiple endpoints at once
3.
Default Template β€” Set a standard starting response for all new endpoints
4.
Dereferencing β€” Customize components for specific endpoints when needed
5.
OpenAPI Compliance β€” Components align with OpenAPI specification standards
Benefits:
Consistency β€” All endpoints follow the same patterns
Efficiency β€” Update once, apply everywhere
Maintainability β€” Easier to manage and evolve your API
Better Documentation β€” Clear, consistent API documentation

What's Next?#

Now that your User module has well-structured endpoints with reusable components, the next step is to secure your API with authentication. In the next article, we'll learn how to set up authentication schemes to protect endpoints that require user login.
Continue with Setting Up Authentication.
Modified atΒ 2025-12-25 09:47:43
Previous
Designing Endpoints
Next
Setting Up Authentication
Built with