Ejemplos OpenAPI/Swagger

Ejemplos completos de documentación API usando OpenAPI 3.0 y especificaciones Swagger para servicios RESTful

📋 API REST Básica OpenAPI 3.0

🟢 simple ⭐⭐⭐

Especificación OpenAPI 3.0 completa para API REST de gestión de usuarios con operaciones CRUD

⏱️ 20 min 🏷️ openapi, api-documentation, rest
Prerequisites: REST API concepts, JSON/YAML
{
  "openapi": "3.0.3",
  "info": {
    "title": "User Management API",
    "description": "A simple REST API for managing users with CRUD operations",
    "version": "1.0.0",
    "contact": {
      "name": "API Support",
      "email": "[email protected]",
      "url": "https://example.com/support"
    },
    "license": {
      "name": "MIT",
      "url": "https://opensource.org/licenses/MIT"
    }
  },
  "servers": [
    {
      "url": "https://api.example.com/v1",
      "description": "Production server"
    },
    {
      "url": "https://staging-api.example.com/v1",
      "description": "Staging server"
    },
    {
      "url": "http://localhost:3000/v1",
      "description": "Development server"
    }
  ],
  "paths": {
    "/users": {
      "get": {
        "summary": "Get all users",
        "description": "Retrieve a paginated list of users",
        "tags": ["Users"],
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Page number for pagination",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Number of items per page",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 10
            }
          },
          {
            "name": "search",
            "in": "query",
            "description": "Search term to filter users",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserListResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      },
      "post": {
        "summary": "Create a new user",
        "description": "Create a new user with the provided information",
        "tags": ["Users"],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateUserRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "User created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          }
        }
      }
    },
    "/users/{userId}": {
      "get": {
        "summary": "Get user by ID",
        "description": "Retrieve a specific user by their ID",
        "tags": ["Users"],
        "parameters": [
          {
            "name": "userId",
            "in": "path",
            "required": true,
            "description": "Unique identifier of the user",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserResponse"
                }
              }
            }
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      },
      "put": {
        "summary": "Update user",
        "description": "Update an existing user's information",
        "tags": ["Users"],
        "parameters": [
          {
            "name": "userId",
            "in": "path",
            "required": true,
            "description": "Unique identifier of the user",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateUserRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "User updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      },
      "delete": {
        "summary": "Delete user",
        "description": "Delete a user by their ID",
        "tags": ["Users"],
        "parameters": [
          {
            "name": "userId",
            "in": "path",
            "required": true,
            "description": "Unique identifier of the user",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "User deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "User": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid",
            "description": "Unique identifier of the user"
          },
          "username": {
            "type": "string",
            "minLength": 3,
            "maxLength": 50,
            "pattern": "^[a-zA-Z0-9_]+$",
            "description": "Unique username"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "User's email address"
          },
          "firstName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 50,
            "description": "User's first name"
          },
          "lastName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 50,
            "description": "User's last name"
          },
          "role": {
            "$ref": "#/components/schemas/UserRole"
          },
          "isActive": {
            "type": "boolean",
            "description": "Whether the user account is active"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "description": "Timestamp when the user was created"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "description": "Timestamp when the user was last updated"
          }
        },
        "required": ["id", "username", "email", "firstName", "lastName", "role", "isActive", "createdAt", "updatedAt"],
        "example": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "username": "johndoe",
          "email": "[email protected]",
          "firstName": "John",
          "lastName": "Doe",
          "role": "user",
          "isActive": true,
          "createdAt": "2024-01-15T10:30:00Z",
          "updatedAt": "2024-01-15T10:30:00Z"
        }
      },
      "UserRole": {
        "type": "string",
        "enum": ["admin", "moderator", "user"],
        "description": "User role in the system"
      },
      "CreateUserRequest": {
        "type": "object",
        "properties": {
          "username": {
            "type": "string",
            "minLength": 3,
            "maxLength": 50,
            "pattern": "^[a-zA-Z0-9_]+$",
            "description": "Unique username"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "User's email address"
          },
          "password": {
            "type": "string",
            "minLength": 8,
            "description": "User's password (minimum 8 characters)"
          },
          "firstName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 50,
            "description": "User's first name"
          },
          "lastName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 50,
            "description": "User's last name"
          },
          "role": {
            "$ref": "#/components/schemas/UserRole"
          }
        },
        "required": ["username", "email", "password", "firstName", "lastName"]
      },
      "UpdateUserRequest": {
        "type": "object",
        "properties": {
          "email": {
            "type": "string",
            "format": "email",
            "description": "User's email address"
          },
          "firstName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 50,
            "description": "User's first name"
          },
          "lastName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 50,
            "description": "User's last name"
          },
          "role": {
            "$ref": "#/components/schemas/UserRole"
          },
          "isActive": {
            "type": "boolean",
            "description": "Whether the user account is active"
          }
        }
      },
      "UserResponse": {
        "allOf": [
          {
            "$ref": "#/components/schemas/User"
          }
        ]
      },
      "UserListResponse": {
        "type": "object",
        "properties": {
          "users": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/User"
            }
          },
          "pagination": {
            "$ref": "#/components/schemas/Pagination"
          }
        }
      },
      "Pagination": {
        "type": "object",
        "properties": {
          "page": {
            "type": "integer",
            "minimum": 1,
            "description": "Current page number"
          },
          "limit": {
            "type": "integer",
            "minimum": 1,
            "description": "Number of items per page"
          },
          "totalItems": {
            "type": "integer",
            "minimum": 0,
            "description": "Total number of items"
          },
          "totalPages": {
            "type": "integer",
            "minimum": 0,
            "description": "Total number of pages"
          }
        }
      },
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "error": {
            "type": "string",
            "description": "Error message"
          },
          "code": {
            "type": "string",
            "description": "Error code"
          },
          "details": {
            "type": "object",
            "description": "Additional error details"
          }
        },
        "required": ["error", "code"]
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Bad request",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "Invalid request data",
              "code": "BAD_REQUEST",
              "details": {
                "field": "email",
                "message": "Invalid email format"
              }
            }
          }
        }
      },
      "Unauthorized": {
        "description": "Unauthorized access",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "Authentication required",
              "code": "UNAUTHORIZED"
            }
          }
        }
      },
      "NotFound": {
        "description": "Resource not found",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "User not found",
              "code": "NOT_FOUND"
            }
          }
        }
      },
      "Conflict": {
        "description": "Resource conflict",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "error": "Username already exists",
              "code": "CONFLICT"
            }
          }
        }
      }
    },
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "description": "JWT token for authentication"
      },
      "apiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "description": "API key for authentication"
      }
    }
  },
  "security": [
    {
      "bearerAuth": []
    },
    {
      "apiKey": []
    }
  ],
  "tags": [
    {
      "name": "Users",
      "description": "User management operations"
    }
  ]
}

💻 API de Comercio Electrónico OpenAPI 3.0

🟡 intermediate ⭐⭐⭐⭐

Especificación API de comercio electrónico completa con gestión de productos, pedidos, pagos e inventario

⏱️ 30 min 🏷️ openapi, ecommerce, api-design
Prerequisites: OpenAPI basics, e-commerce concepts, YAML
openapi: 3.0.3
info:
  title: E-commerce Platform API
  description: A complete e-commerce API for managing products, orders, payments, and inventory
  version: 2.1.0
  contact:
    name: API Team
    email: [email protected]
    url: https://ecommerce.com/api-support
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html

servers:
  - url: https://api.ecommerce.com/v2
    description: Production server
  - url: https://staging-api.ecommerce.com/v2
    description: Staging server
  - url: http://localhost:8080/v2
    description: Development server

paths:
  /products:
    get:
      summary: List products
      description: Retrieve a paginated list of products with filtering and sorting options
      tags:
        - Products
      parameters:
        - name: page
          in: query
          description: Page number for pagination
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          description: Number of products per page
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: category
          in: query
          description: Filter by category ID
          schema:
            type: string
            format: uuid
        - name: minPrice
          in: query
          description: Minimum price filter
          schema:
            type: number
            minimum: 0
        - name: maxPrice
          in: query
          description: Maximum price filter
          schema:
            type: number
            minimum: 0
        - name: sortBy
          in: query
          description: Sort field
          schema:
            type: string
            enum: [price, name, createdAt, rating, sales]
            default: createdAt
        - name: sortOrder
          in: query
          description: Sort order
          schema:
            type: string
            enum: [asc, desc]
            default: desc
        - name: search
          in: query
          description: Search term
          schema:
            type: string
      responses:
        '200':
          description: Products retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProductListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'

    post:
      summary: Create product
      description: Create a new product
      tags:
        - Products
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateProductRequest'
      responses:
        '201':
          description: Product created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProductResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /products/{productId}:
    get:
      summary: Get product details
      description: Retrieve detailed information about a specific product
      tags:
        - Products
      parameters:
        - name: productId
          in: path
          required: true
          description: Product ID
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Product retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProductDetailResponse'
        '404':
          $ref: '#/components/responses/NotFound'

  /orders:
    get:
      summary: List orders
      description: Retrieve user's orders with pagination and filtering
      tags:
        - Orders
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 50
            default: 10
        - name: status
          in: query
          description: Filter by order status
          schema:
            $ref: '#/components/schemas/OrderStatus'
        - name: startDate
          in: query
          description: Filter orders from this date
          schema:
            type: string
            format: date
        - name: endDate
          in: query
          description: Filter orders until this date
          schema:
            type: string
            format: date
      responses:
        '200':
          description: Orders retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'

    post:
      summary: Create order
      description: Create a new order from shopping cart
      tags:
        - Orders
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateOrderRequest'
      responses:
        '201':
          description: Order created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /orders/{orderId}:
    get:
      summary: Get order details
      description: Retrieve detailed information about a specific order
      tags:
        - Orders
      security:
        - bearerAuth: []
      parameters:
        - name: orderId
          in: path
          required: true
          description: Order ID
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Order retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderDetailResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'

  /payments:
    post:
      summary: Process payment
      description: Process payment for an order
      tags:
        - Payments
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProcessPaymentRequest'
      responses:
        '200':
          description: Payment processed successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PaymentResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          description: Payment failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PaymentErrorResponse'

  /inventory/{productId}:
    get:
      summary: Get product inventory
      description: Get current inventory levels for a product
      tags:
        - Inventory
      parameters:
        - name: productId
          in: path
          required: true
          description: Product ID
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Inventory retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InventoryResponse'

components:
  schemas:
    Product:
      type: object
      properties:
        id:
          type: string
          format: uuid
          description: Product unique identifier
        name:
          type: string
          maxLength: 200
          description: Product name
        description:
          type: string
          maxLength: 2000
          description: Product description
        price:
          type: number
          format: decimal
          minimum: 0
          description: Product price
        originalPrice:
          type: number
          format: decimal
          minimum: 0
          description: Original price (if discounted)
        sku:
          type: string
          maxLength: 50
          description: Stock keeping unit
        category:
          $ref: '#/components/schemas/Category'
        images:
          type: array
          items:
            $ref: '#/components/schemas/ProductImage'
        attributes:
          type: array
          items:
            $ref: '#/components/schemas/ProductAttribute'
        rating:
          type: number
          format: float
          minimum: 0
          maximum: 5
          description: Average customer rating
        reviewCount:
          type: integer
          minimum: 0
          description: Number of customer reviews
        isActive:
          type: boolean
          description: Whether the product is active
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
      required: [id, name, description, price, sku, category, isActive, createdAt, updatedAt]

    Category:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
          maxLength: 100
        slug:
          type: string
          maxLength: 100
        parentId:
          type: string
          format: uuid
          nullable: true

    ProductImage:
      type: object
      properties:
        url:
          type: string
          format: uri
        alt:
          type: string
          maxLength: 200
        isPrimary:
          type: boolean

    ProductAttribute:
      type: object
      properties:
        name:
          type: string
          maxLength: 100
        value:
          type: string
          maxLength: 200

    CreateProductRequest:
      type: object
      required: [name, description, price, sku, categoryId]
      properties:
        name:
          type: string
          maxLength: 200
        description:
          type: string
          maxLength: 2000
        price:
          type: number
          format: decimal
          minimum: 0
        originalPrice:
          type: number
          format: decimal
          minimum: 0
        sku:
          type: string
          maxLength: 50
        categoryId:
          type: string
          format: uuid
        images:
          type: array
          items:
            type: string
            format: uri
        attributes:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
                maxLength: 100
              value:
                type: string
                maxLength: 200

    ProductResponse:
      allOf:
        - $ref: '#/components/schemas/Product'
        - type: object
          properties:
            inventory:
              $ref: '#/components/schemas/InventoryInfo'

    ProductDetailResponse:
      allOf:
        - $ref: '#/components/schemas/ProductResponse'
        - type: object
          properties:
            reviews:
              type: array
              items:
                $ref: '#/components/schemas/ProductReview'
            relatedProducts:
              type: array
              items:
                $ref: '#/components/schemas/Product'

    ProductReview:
      type: object
      properties:
        id:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        username:
          type: string
        rating:
          type: integer
          minimum: 1
          maximum: 5
        comment:
          type: string
          maxLength: 1000
        createdAt:
          type: string
          format: date-time

    InventoryInfo:
      type: object
      properties:
        quantity:
          type: integer
          minimum: 0
        available:
          type: integer
          minimum: 0
        reserved:
          type: integer
          minimum: 0
        lowStockThreshold:
          type: integer
          minimum: 0

    OrderStatus:
      type: string
      enum: [pending, confirmed, processing, shipped, delivered, cancelled, refunded]
      description: Order status

    Order:
      type: object
      properties:
        id:
          type: string
          format: uuid
        orderNumber:
          type: string
          description: Human-readable order number
        userId:
          type: string
          format: uuid
        status:
          $ref: '#/components/schemas/OrderStatus'
        items:
          type: array
          items:
            $ref: '#/components/schemas/OrderItem'
        subtotal:
          type: number
          format: decimal
          minimum: 0
        tax:
          type: number
          format: decimal
          minimum: 0
        shipping:
          type: number
          format: decimal
          minimum: 0
        total:
          type: number
          format: decimal
          minimum: 0
        currency:
          type: string
          length: 3
          default: USD
        shippingAddress:
          $ref: '#/components/schemas/Address'
        billingAddress:
          $ref: '#/components/schemas/Address'
        paymentMethod:
          type: string
        paymentStatus:
          type: string
          enum: [pending, paid, failed, refunded]
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time

    OrderItem:
      type: object
      properties:
        productId:
          type: string
          format: uuid
        productSku:
          type: string
        productName:
          type: string
        quantity:
          type: integer
          minimum: 1
        unitPrice:
          type: number
          format: decimal
          minimum: 0
        totalPrice:
          type: number
          format: decimal
          minimum: 0

    Address:
      type: object
      properties:
        street:
          type: string
          maxLength: 200
        city:
          type: string
          maxLength: 100
        state:
          type: string
          maxLength: 100
        zipCode:
          type: string
          maxLength: 20
        country:
          type: string
          maxLength: 100

    CreateOrderRequest:
      type: object
      required: [items, shippingAddress, paymentMethod]
      properties:
        items:
          type: array
          items:
            type: object
            properties:
              productId:
                type: string
                format: uuid
              quantity:
                type: integer
                minimum: 1
        shippingAddress:
          $ref: '#/components/schemas/Address'
        billingAddress:
          $ref: '#/components/schemas/Address'
        paymentMethod:
          type: string
        couponCode:
          type: string

    PaymentMethod:
      type: string
      enum: [credit_card, debit_card, paypal, stripe, apple_pay, google_pay]

    ProcessPaymentRequest:
      type: object
      required: [orderId, paymentMethod]
      properties:
        orderId:
          type: string
          format: uuid
        paymentMethod:
          $ref: '#/components/schemas/PaymentMethod'
        paymentDetails:
          oneOf:
            - $ref: '#/components/schemas/CreditCardPayment'
            - $ref: '#/components/schemas/PayPalPayment'

    CreditCardPayment:
      type: object
      required: [cardNumber, expiryMonth, expiryYear, cvv, cardholderName]
      properties:
        cardNumber:
          type: string
          pattern: '^[0-9]{16}$'
        expiryMonth:
          type: integer
          minimum: 1
          maximum: 12
        expiryYear:
          type: integer
          minimum: 2024
        cvv:
          type: string
          pattern: '^[0-9]{3,4}$'
        cardholderName:
          type: string
          maxLength: 100

    PayPalPayment:
      type: object
      required: [paypalEmail]
      properties:
        paypalEmail:
          type: string
          format: email

    PaymentResponse:
      type: object
      properties:
        paymentId:
          type: string
          format: uuid
        orderId:
          type: string
          format: uuid
        status:
          type: string
          enum: [success, failed, pending]
        amount:
          type: number
          format: decimal
        currency:
          type: string
          transactionId:
          type: string
        paymentMethod:
          $ref: '#/components/schemas/PaymentMethod'
        processedAt:
          type: string
          format: date-time

    ProductListResponse:
      type: object
      properties:
        products:
          type: array
          items:
            $ref: '#/components/schemas/ProductResponse'
        pagination:
          $ref: '#/components/schemas/Pagination'
        filters:
          type: object
          properties:
            categories:
              type: array
              items:
                $ref: '#/components/schemas/Category'
            priceRange:
              type: object
              properties:
                min:
                  type: number
                max:
                  type: number

    OrderListResponse:
      type: object
      properties:
        orders:
          type: array
          items:
            $ref: '#/components/schemas/Order'
        pagination:
          $ref: '#/components/schemas/Pagination'

    Pagination:
      type: object
      properties:
        page:
          type: integer
          minimum: 1
        limit:
          type: integer
          minimum: 1
        totalItems:
          type: integer
          minimum: 0
        totalPages:
          type: integer
          minimum: 0
        hasNext:
          type: boolean
        hasPrev:
          type: boolean

    ErrorResponse:
      type: object
      required: [error, code]
      properties:
        error:
          type: string
        code:
          type: string
        message:
          type: string
        details:
          type: object

  responses:
    BadRequest:
      description: Bad request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

    Forbidden:
      description: Forbidden
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT authentication token

tags:
  - name: Products
    description: Product management endpoints
  - name: Orders
    description: Order management endpoints
  - name: Payments
    description: Payment processing endpoints
  - name: Inventory
    description: Inventory management endpoints

📋 Especificación Webhooks OpenAPI 3.0

🟡 intermediate ⭐⭐⭐

Especificación API webhooks para notificaciones de eventos en tiempo real con seguridad y mecanismos de reintento

⏱️ 25 min 🏷️ openapi, webhooks, events, api
Prerequisites: OpenAPI basics, webhook concepts, event-driven architecture
{
  "openapi": "3.0.3",
  "info": {
    "title": "Webhook Events API",
    "description": "API specification for webhook event notifications and management",
    "version": "1.2.0",
    "contact": {
      "name": "Webhook Support",
      "email": "[email protected]"
    }
  },
  "servers": [
    {
      "url": "https://api.example.com/webhooks/v1",
      "description": "Production webhook API"
    }
  ],
  "paths": {
    "/webhooks": {
      "get": {
        "summary": "List webhooks",
        "description": "Retrieve all configured webhooks for the authenticated user",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Webhooks retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "webhooks": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Webhook"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Create webhook",
        "description": "Create a new webhook endpoint",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateWebhookRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Webhook created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Webhook"
                }
              }
            }
          }
        }
      }
    },
    "/webhooks/{webhookId}": {
      "get": {
        "summary": "Get webhook details",
        "description": "Retrieve details of a specific webhook",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "webhookId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Webhook details retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookDetail"
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "Update webhook",
        "description": "Update an existing webhook configuration",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "webhookId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateWebhookRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Webhook updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Webhook"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "Delete webhook",
        "description": "Delete a webhook endpoint",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "webhookId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Webhook deleted successfully"
          }
        }
      }
    },
    "/webhooks/{webhookId}/test": {
      "post": {
        "summary": "Test webhook",
        "description": "Send a test event to the webhook endpoint",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "webhookId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "eventType": {
                    "type": "string",
                    "description": "Type of test event to send",
                    "enum": ["user.created", "order.completed", "payment.failed"]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Test webhook sent successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookTestResult"
                }
              }
            }
          }
        }
      }
    },
    "/webhooks/{webhookId}/logs": {
      "get": {
        "summary": "Get webhook delivery logs",
        "description": "Retrieve delivery logs for a specific webhook",
        "tags": ["Webhooks"],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "webhookId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": ["success", "failed", "pending"]
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 20
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Webhook logs retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "logs": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/WebhookLog"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "webhooks": {
    "user.created": {
      "description": "Triggered when a new user account is created",
      "post": {
        "summary": "User Created Event",
        "requestBody": {
          "description": "User creation event payload",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UserCreatedEvent"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Webhook processed successfully"
          },
          "400": {
            "description": "Invalid webhook payload or endpoint"
          }
        }
      }
    },
    "order.completed": {
      "description": "Triggered when an order is completed",
      "post": {
        "summary": "Order Completed Event",
        "requestBody": {
          "description": "Order completion event payload",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OrderCompletedEvent"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Webhook processed successfully"
          }
        }
      }
    },
    "payment.failed": {
      "description": "Triggered when a payment fails",
      "post": {
        "summary": "Payment Failed Event",
        "requestBody": {
          "description": "Payment failure event payload",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PaymentFailedEvent"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Webhook processed successfully"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Webhook": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "url": {
            "type": "string",
            "format": "uri",
            "description": "Webhook endpoint URL"
          },
          "events": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "List of events this webhook subscribes to"
          },
          "isActive": {
            "type": "boolean",
            "description": "Whether the webhook is active"
          },
          "secret": {
            "type": "string",
            "description": "Webhook secret for signature validation"
          },
          "retryConfig": {
            "$ref": "#/components/schemas/RetryConfig"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        },
        "required": ["id", "url", "events", "isActive", "createdAt", "updatedAt"]
      },
      "WebhookDetail": {
        "allOf": [
          {
            "$ref": "#/components/schemas/Webhook"
          },
          {
            "type": "object",
            "properties": {
              "deliveryStats": {
                "$ref": "#/components/schemas/DeliveryStats"
              },
              "recentDeliveries": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/WebhookLog"
                }
              }
            }
          }
        ]
      },
      "CreateWebhookRequest": {
        "type": "object",
        "required": ["url", "events"],
        "properties": {
          "url": {
            "type": "string",
            "format": "uri",
            "description": "Webhook endpoint URL"
          },
          "events": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "List of events to subscribe to"
          },
          "secret": {
            "type": "string",
            "minLength": 8,
            "description": "Optional webhook secret for signature validation"
          },
          "retryConfig": {
            "$ref": "#/components/schemas/RetryConfig"
          }
        }
      },
      "UpdateWebhookRequest": {
        "type": "object",
        "properties": {
          "url": {
            "type": "string",
            "format": "uri"
          },
          "events": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "isActive": {
            "type": "boolean"
          },
          "secret": {
            "type": "string",
            "minLength": 8
          },
          "retryConfig": {
            "$ref": "#/components/schemas/RetryConfig"
          }
        }
      },
      "RetryConfig": {
        "type": "object",
        "properties": {
          "maxRetries": {
            "type": "integer",
            "minimum": 0,
            "maximum": 10,
            "default": 3
          },
          "retryDelay": {
            "type": "integer",
            "minimum": 1,
            "default": 60
          },
          "backoffMultiplier": {
            "type": "number",
            "minimum": 1,
            "maximum": 5,
            "default": 2
          }
        }
      },
      "DeliveryStats": {
        "type": "object",
        "properties": {
          "totalDeliveries": {
            "type": "integer",
            "minimum": 0
          },
          "successfulDeliveries": {
            "type": "integer",
            "minimum": 0
          },
          "failedDeliveries": {
            "type": "integer",
            "minimum": 0
          },
          "pendingDeliveries": {
            "type": "integer",
            "minimum": 0
          },
          "successRate": {
            "type": "number",
            "format": "float",
            "minimum": 0,
            "maximum": 100
          },
          "lastDeliveryAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "WebhookLog": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "webhookId": {
            "type": "string",
            "format": "uuid"
          },
          "eventType": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": ["success", "failed", "pending", "retrying"]
          },
          "httpStatus": {
            "type": "integer"
          },
          "attempt": {
            "type": "integer",
            "minimum": 1
          },
          "responseTime": {
            "type": "integer",
            "description": "Response time in milliseconds"
          },
          "errorMessage": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "nextRetryAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "WebhookTestResult": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean"
          },
          "httpStatus": {
            "type": "integer"
          },
          "responseTime": {
            "type": "integer"
          },
          "response": {
            "type": "string"
          },
          "error": {
            "type": "string"
          }
        }
      },
      "UserCreatedEvent": {
        "type": "object",
        "properties": {
          "eventId": {
            "type": "string",
            "format": "uuid"
          },
          "eventType": {
            "type": "string",
            "enum": ["user.created"]
          },
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "data": {
            "type": "object",
            "properties": {
              "userId": {
                "type": "string",
                "format": "uuid"
              },
              "email": {
                "type": "string",
                "format": "email"
              },
              "username": {
                "type": "string"
              },
              "firstName": {
                "type": "string"
              },
              "lastName": {
                "type": "string"
              }
            }
          }
        }
      },
      "OrderCompletedEvent": {
        "type": "object",
        "properties": {
          "eventId": {
            "type": "string",
            "format": "uuid"
          },
          "eventType": {
            "type": "string",
            "enum": ["order.completed"]
          },
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "data": {
            "type": "object",
            "properties": {
              "orderId": {
                "type": "string",
                "format": "uuid"
              },
              "orderNumber": {
                "type": "string"
              },
              "userId": {
                "type": "string",
                "format": "uuid"
              },
              "total": {
                "type": "number",
                "format": "decimal"
              },
              "currency": {
                "type": "string"
              },
              "itemCount": {
                "type": "integer"
              }
            }
          }
        }
      },
      "PaymentFailedEvent": {
        "type": "object",
        "properties": {
          "eventId": {
            "type": "string",
            "format": "uuid"
          },
          "eventType": {
            "type": "string",
            "enum": ["payment.failed"]
          },
          "timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "data": {
            "type": "object",
            "properties": {
              "paymentId": {
                "type": "string",
                "format": "uuid"
              },
              "orderId": {
                "type": "string",
                "format": "uuid"
              },
              "userId": {
                "type": "string",
                "format": "uuid"
              },
              "amount": {
                "type": "number",
                "format": "decimal"
              },
              "currency": {
                "type": "string"
              },
              "failureReason": {
                "type": "string"
              },
              "errorCode": {
                "type": "string"
              }
            }
          }
        }
      }
    },
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  },
  "tags": [
    {
      "name": "Webhooks",
      "description": "Webhook management and event endpoints"
    }
  ]
}