Chapter 3: WSO2 API Manager

Overview

WSO2 API Manager (APIM) is a complete solution for designing, publishing, and managing APIs. It covers the full API lifecycle, from creation to retirement.

API Lifecycle

Lifecycle States

CREATE → PUBLISH → BLOCK → DEPRECATE → RETIRE
   ↑         ↓
   └─────────┘
  (PROTOTYPE)

State Descriptions:

  1. CREATED: API designed but not yet available
  2. PROTOTYPED: Early version for testing (no subscriptions needed)
  3. PUBLISHED: Available for subscription and use
  4. BLOCKED: Temporarily unavailable (existing subscriptions remain)
  5. DEPRECATED: Marked for removal (no new subscriptions)
  6. RETIRED: Removed from store (all access blocked)

Lifecycle Transitions

# Typical flow
Created → Published     # Make available
Published → Deprecated  # Signal upcoming removal
Deprecated → Retired    # Remove completely

# Emergency flow
Published → Blocked     # Temporary outage
Blocked → Published     # Restore service

API Types

1. REST API

Most common API type for modern applications.

Creation Example:

{
  "name": "PizzaShackAPI",
  "version": "1.0.0",
  "context": "/pizzashack/1.0.0",
  "type": "HTTP",
  "transport": ["http", "https"],
  "operations": [
    {
      "target": "/menu",
      "verb": "GET",
      "throttlingPolicy": "Unlimited"
    },
    {
      "target": "/order",
      "verb": "POST",
      "throttlingPolicy": "10KPerMin"
    }
  ]
}

Use Cases:

  • Mobile backends
  • Web services
  • Microservices APIs
  • Third-party integrations

2. SOAP API

Support for legacy SOAP services.

WSDL Import:

<wsdl:definitions>
  <wsdl:service name="WeatherService">
    <wsdl:port name="WeatherSoap" binding="tns:WeatherSoap">
      <soap:address location="http://backend/weather" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

Use Cases:

  • Enterprise integrations
  • Banking and financial services
  • Healthcare systems
  • Government services

3. GraphQL API

Query language for APIs with flexible data fetching.

Schema Example:

type Query {
  user(id: ID!): User
  users: [User]
}

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post]
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
}

Use Cases:

  • Complex data requirements
  • Mobile apps with bandwidth constraints
  • Aggregating multiple data sources

4. WebSocket API

Bidirectional, real-time communication.

Configuration:

apiName: ChatAPI
version: 1.0.0
context: /chat
transport: ws, wss
topics:
  - /room/{roomId}
  - /private/{userId}

Use Cases:

  • Chat applications
  • Real-time notifications
  • Live data feeds
  • Gaming

5. Streaming API

Server-sent events and event streams.

Use Cases:

  • Real-time analytics dashboards
  • Stock tickers
  • News feeds
  • IoT data streams

API Design

Best Practices

1. Naming Conventions:

Good:
GET /api/v1/users
GET /api/v1/users/{id}
POST /api/v1/users
PUT /api/v1/users/{id}
DELETE /api/v1/users/{id}

Bad:
GET /api/getUsersList
POST /api/createNewUser
GET /api/user-details?id=123

2. Versioning:

URL Versioning:     /api/v1/users
Header Versioning:  Accept: application/vnd.api.v1+json
Query Parameter:    /api/users?version=1

3. Resource Design:

  • Use nouns, not verbs
  • Use plurals for collections
  • Nest resources logically
  • Keep URLs simple and intuitive

4. HTTP Methods:

GET    - Retrieve resource(s)
POST   - Create new resource
PUT    - Update entire resource
PATCH  - Partial update
DELETE - Remove resource

API Definition (OpenAPI/Swagger)

Example OpenAPI 3.0:

openapi: 3.0.0
info:
  title: Pizza Shack API
  version: 1.0.0
  description: Order pizzas online

servers:
  - url: https://api.pizzashack.com/v1

paths:
  /menu:
    get:
      summary: Get pizza menu
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Pizza'

  /order:
    post:
      summary: Place an order
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Order'
      responses:
        '201':
          description: Order created

components:
  schemas:
    Pizza:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        price:
          type: number
        
    Order:
      type: object
      required:
        - pizzaId
        - quantity
      properties:
        pizzaId:
          type: string
        quantity:
          type: integer
        address:
          type: string

API Gateway

Gateway Functions

1. Request Routing:

Client → Gateway → Backend Service
         |
         ├→ Load balancing
         ├→ Service discovery
         └→ Failover

2. Security Enforcement:

  • Token validation
  • Scope verification
  • IP whitelisting
  • Certificate validation

3. Rate Limiting:

Tier             Requests/Minute
───────────────────────────────
Bronze           10
Silver           100
Gold             1000
Unlimited        No limit

4. Transformation:

  • Request/response modification
  • Protocol conversion (REST ↔ SOAP)
  • Content enrichment
  • Header manipulation

5. Caching:

[apim.cache.gateway_token]
enable = true
expiry_time = 900

[apim.cache.resource]
enable = true
expiry_time = 300

Gateway Deployment Patterns

1. Single Gateway:

Clients → Gateway → Backends

2. Multiple Gateways (Load Balanced):

              Load Balancer
                    │
        ┌───────────┼───────────┐
        │           │           │
    Gateway1    Gateway2    Gateway3
        │           │           │
        └───────────┴───────────┘
                    │
                Backends

3. Gateway per Environment:

Dev Clients → Dev Gateway → Dev Backends
QA Clients → QA Gateway → QA Backends
Prod Clients → Prod Gateway → Prod Backends

Publisher Portal

Creating an API

Step-by-Step:

  1. Design API:

    • Choose API type (REST, SOAP, GraphQL, etc.)
    • Define resources and operations
    • Import OpenAPI definition (optional)
  2. Configure:

    • Set context and version
    • Configure backend endpoint
    • Define mediation logic
  3. Manage Lifecycle:

    • Save as draft (CREATED)
    • Deploy and publish
  4. Configure Access:

    • Set visibility (public, private, restricted)
    • Configure subscription tiers
    • Enable/disable security

REST API Creation (UI):

1. Click "Create API" → "Design a New REST API"
2. Enter API details:
   - Name: PizzaShackAPI
   - Context: /pizzashack
   - Version: 1.0.0
3. Define resources:
   - GET /menu
   - POST /order
   - GET /order/{orderId}
4. Configure endpoint:
   - Production: https://backend.pizzashack.com
   - Sandbox: https://sandbox.pizzashack.com
5. Save and Publish

API Configuration

Backend Endpoints:

{
  "production_endpoints": {
    "url": "https://prod.backend.com/api",
    "config": {
      "retryCount": 3,
      "retryDelay": 100,
      "timeout": 30000
    }
  },
  "sandbox_endpoints": {
    "url": "https://sandbox.backend.com/api"
  }
}

Business Information:

businessOwner: John Doe
businessOwnerEmail: john@pizzashack.com
technicalOwner: Jane Smith
technicalOwnerEmail: jane@pizzashack.com

CORS Configuration:

[apim.cors]
allow_origins = ["*"]
allow_methods = ["GET","POST","PUT","DELETE","PATCH","OPTIONS"]
allow_headers = ["authorization","content-type"]
allow_credentials = true

Developer Portal

For API Consumers

1. Discover APIs:

  • Browse API catalog
  • Search and filter
  • View documentation
  • Check ratings and reviews

2. Subscribe to APIs:

Developer → Create Application → Subscribe to API → Generate Keys

3. Application Types:

  • Web Application: Server-side apps
  • Mobile Application: Native mobile apps
  • Single Page Application: Client-side apps
  • IoT Device: IoT and embedded devices

4. Subscription Workflow:

1. Create Application (e.g., "MyWebApp")
2. Subscribe to API with chosen tier (Bronze/Silver/Gold)
3. Generate Keys:
   - Production keys
   - Sandbox keys
4. Receive:
   - Consumer Key
   - Consumer Secret
   - Access Token (optional)

Generating Access Tokens

OAuth2 Password Grant:

curl -k -d "grant_type=password&username=user&password=pass" \
  -H "Authorization: Basic <base64(consumerKey:consumerSecret)>" \
  https://gateway:8243/token

Response:

{
  "access_token": "eyJ4NXQiOiJNell4TW1Ga09H...",
  "refresh_token": "eyJ4NXQiOiJNell4TW1Ga09H...",
  "token_type": "Bearer",
  "expires_in": 3600
}

Using the Token:

curl -H "Authorization: Bearer <access_token>" \
  https://gateway:8243/pizzashack/1.0.0/menu

Rate Limiting and Throttling

Throttling Tiers

Subscription Tiers (API level):

Bronze:    10 requests per minute
Silver:    100 requests per minute  
Gold:      1000 requests per minute
Unlimited: No limit

Advanced Throttling:

# API level
throttlingTier: Gold

# Resource level
GET /menu:
  throttlingTier: Unlimited
  
POST /order:
  throttlingTier: Silver

# Application level
Application: MyApp
  throttlingTier: Gold

Custom Throttling Policies

Conditional Policy:

<throttlePolicy>
  <condition>
    <header name="X-Priority" value="high"/>
  </condition>
  <limit>10000 per hour</limit>
</throttlePolicy>

IP-Based Throttling:

<throttlePolicy type="IP">
  <limit>100 per minute</limit>
</throttlePolicy>

API Analytics

Metrics Collected

Request Analytics:

  • Total requests
  • Success/failure rates
  • Response times
  • Error codes

Usage Analytics:

  • API popularity
  • Top consumers
  • Geographic distribution
  • Device types

Business Analytics:

  • Revenue (if monetization enabled)
  • Subscription trends
  • API adoption rates

Analytics Dashboard

Key Metrics:

┌────────────────────────────────────┐
│  Total Requests:     1,234,567     │
│  Success Rate:       99.2%         │
│  Avg Response Time:  45ms          │
│  Errors:             9,876         │
└────────────────────────────────────┘

Top APIs:
1. UserAPI         - 500K requests
2. ProductAPI      - 300K requests
3. OrderAPI        - 200K requests

Top Apps:
1. MobileApp       - 400K requests
2. WebApp          - 350K requests
3. PartnerApp      - 250K requests

API Security

Authentication Methods

1. OAuth 2.0 (Recommended):

Client → Request Token → Gateway → Validate → Backend

2. API Key:

curl -H "apikey: xyz123" https://gateway/api/resource

3. Mutual TLS:

Client Cert → Gateway Validation → Backend

4. JWT:

curl -H "Authorization: Bearer <JWT>" https://gateway/api/resource

Authorization

Scope-Based:

scopes:
  - name: read_menu
    description: Read menu items
  - name: place_order
    description: Place orders
  - name: admin
    description: Administrative access

resources:
  GET /menu:
    scopes: [read_menu]
  POST /order:
    scopes: [place_order]
  DELETE /order/{id}:
    scopes: [admin]

API Monetization

Billing Plans

Setup:

  1. Enable monetization in API
  2. Define billing plans
  3. Integrate payment gateway
  4. Configure pricing tiers

Example Pricing:

Free Tier:    0 requests    $0/month
Basic:        1,000 req     $10/month
Pro:          10,000 req    $50/month
Enterprise:   Unlimited     $500/month

API Revisions

Version Management

Creating New Version:

PizzaShackAPI v1.0.0 → Create New Version → v2.0.0

Version Strategies:

  1. Breaking Changes: New major version (v1 → v2)
  2. Non-Breaking: New minor version (v1.0 → v1.1)
  3. Bug Fixes: Patch version (v1.0.0 → v1.0.1)

Deprecation Process:

v1.0.0 (PUBLISHED)
   ↓
Announce v2.0.0 release
   ↓
v1.0.0 (DEPRECATED) + v2.0.0 (PUBLISHED)
   ↓
Grace period (3-6 months)
   ↓
v1.0.0 (RETIRED)

Micro Gateway

Lightweight Alternative

Benefits:

  • Immutable
  • Fast startup
  • Low resource usage
  • Container-friendly
  • No runtime dependencies on control plane

Deployment:

# Generate gateway for specific API
micro-gw setup pizzashack-project --api pizzashack:1.0.0

# Build gateway
micro-gw build pizzashack-project

# Run gateway
micro-gw start pizzashack-project

Use Cases:

  • Microservices architecture
  • Kubernetes/Docker deployments
  • Edge computing
  • Per-API gateways

Key Takeaways

  • API Manager provides complete API lifecycle management
  • Five main components: Publisher, Developer Portal, Gateway, Key Manager, Traffic Manager
  • Supports REST, SOAP, GraphQL, WebSocket, and Streaming APIs
  • Gateway handles routing, security, rate limiting, and transformation
  • OAuth 2.0 is the recommended authentication method
  • Analytics provide insights into API usage and performance
  • Micro Gateway is ideal for cloud-native deployments

Next Steps

Proceed to Chapter 4: WSO2 Integration to learn about enterprise integration patterns and message mediation.