Skip to main content
OCIServerlessintermediate

OCI API Gateway Guide

Build and secure RESTful APIs with OCI API Gateway: deployments, routes, JWT authentication, rate limiting, CORS, and request transformations.

CloudToolStack Team24 min readPublished Mar 14, 2026

Prerequisites

  • Understanding of REST API concepts and HTTP
  • OCI account with API Gateway permissions

Introduction to OCI API Gateway

OCI API Gateway is a fully managed service that enables you to create, publish, secure, and monitor RESTful APIs at scale. It acts as a single entry point for API consumers, providing traffic management, request/response transformation, authentication, authorization, rate limiting, and CORS handling. The gateway sits between your API clients and your backend services, which can be OCI Functions, compute instances, OKE services, or any HTTP-accessible endpoint.

API Gateway supports multiple deployment models: public gateways that are accessible from the internet, and private gateways that are only accessible within your VCN. Each gateway can host multiple API deployments, and each deployment defines a set of routes that map URL paths to backend services with individual policies for authentication, rate limiting, and request transformation.

This guide walks through creating gateways and deployments, configuring routes with different backend types, implementing JWT authentication, setting up rate limiting and CORS, using request/response transformations, and establishing production best practices for API management on OCI.

API Gateway Pricing

OCI API Gateway pricing is based on the number of API calls processed per month. The first 1 million API calls per month are included at no charge. Beyond that, pricing is approximately $3.00 per million API calls. There are no charges for gateway instances, deployments, or idle time, making it cost-effective for both low-traffic and high-traffic APIs.

Creating an API Gateway

An API gateway is the foundational resource that hosts your API deployments. Each gateway is associated with a VCN subnet and can be either public (internet-facing) or private (VCN-internal). A single gateway can host multiple API deployments, each with its own base path and route configuration.

When creating a gateway, you must configure the subnet, which determines the network accessibility. For public gateways, use a public subnet with an internet gateway. For private gateways, use a private subnet. The gateway automatically provisions a load balancer behind the scenes to handle traffic distribution.

bash
# Create a public API gateway
oci api-gateway gateway create \
  --compartment-id $C \
  --display-name "my-api-gateway" \
  --endpoint-type "PUBLIC" \
  --subnet-id <public-subnet-ocid> \
  --wait-for-state ACTIVE

# Create a private API gateway (VCN-internal only)
oci api-gateway gateway create \
  --compartment-id $C \
  --display-name "internal-api-gateway" \
  --endpoint-type "PRIVATE" \
  --subnet-id <private-subnet-ocid> \
  --wait-for-state ACTIVE

# List all gateways
oci api-gateway gateway list \
  --compartment-id $C \
  --query 'data.items[].{"display-name":"display-name", hostname:hostname, "endpoint-type":"endpoint-type", "lifecycle-state":"lifecycle-state"}' \
  --output table

# Get gateway details including the hostname
oci api-gateway gateway get \
  --gateway-id <gateway-ocid> \
  --query 'data.{hostname:hostname, "endpoint-type":"endpoint-type", "time-created":"time-created"}'

Deployments and Routes

An API deployment defines a collection of routes under a common base path. Each route maps an HTTP method and URL path pattern to a backend service. The deployment is the primary unit of API configuration, containing all the routing rules, security policies, and transformation logic for a logical API.

Routes support path parameters (e.g., /users/{userId}), wildcard matching, and multiple HTTP methods on the same path. Each route can have its own backend type, authentication requirements, and rate limiting configuration, providing fine-grained control over API behavior.

OCI API Gateway supports several backend types:

HTTP Backend: Routes requests to any HTTP/HTTPS endpoint, including compute instances, OKE services, or external APIs.

Oracle Functions: Invokes an OCI Function directly, enabling serverless API backends without managing any infrastructure.

Stock Response: Returns a static response without calling any backend. Useful for health check endpoints, mock APIs, and maintenance pages.

bash
# Create an API deployment with multiple routes
oci api-gateway deployment create \
  --compartment-id $C \
  --gateway-id <gateway-ocid> \
  --display-name "user-api-v1" \
  --path-prefix "/api/v1" \
  --specification '{
    "routes": [
      {
        "path": "/users",
        "methods": ["GET"],
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/users",
          "connectTimeoutInSeconds": 10,
          "readTimeoutInSeconds": 30,
          "sendTimeoutInSeconds": 10
        }
      },
      {
        "path": "/users/{userId}",
        "methods": ["GET", "PUT", "DELETE"],
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/users/$\{request.path[userId]}"
        }
      },
      {
        "path": "/users",
        "methods": ["POST"],
        "backend": {
          "type": "ORACLE_FUNCTIONS_BACKEND",
          "functionId": "<create-user-function-ocid>"
        }
      },
      {
        "path": "/health",
        "methods": ["GET"],
        "backend": {
          "type": "STOCK_RESPONSE_BACKEND",
          "status": 200,
          "body": "{"status": "healthy"}",
          "headers": [{"name": "Content-Type", "value": "application/json"}]
        }
      }
    ]
  }' \
  --wait-for-state ACTIVE

# List deployments on a gateway
oci api-gateway deployment list \
  --compartment-id $C \
  --gateway-id <gateway-ocid> \
  --query 'data.items[].{"display-name":"display-name", "path-prefix":"path-prefix", "lifecycle-state":"lifecycle-state"}' \
  --output table

# Test the API
# curl https://<gateway-hostname>/api/v1/health
# curl https://<gateway-hostname>/api/v1/users
# curl https://<gateway-hostname>/api/v1/users/123

JWT Authentication

OCI API Gateway supports JSON Web Token (JWT) authentication natively, allowing you to secure your APIs without writing authentication code in your backend services. The gateway validates JWT tokens in incoming requests, checks the signature against a trusted issuer's public keys, verifies claims (audience, expiration, issuer), and only forwards requests with valid tokens to the backend.

JWT authentication can be configured at the deployment level (applied to all routes) or at the individual route level for fine-grained control. You can also combine JWT authentication with authorization policies that check specific token claims or scopes before allowing access.

bash
# Deployment with JWT authentication on all routes
oci api-gateway deployment create \
  --compartment-id $C \
  --gateway-id <gateway-ocid> \
  --display-name "secured-api" \
  --path-prefix "/api/v1" \
  --specification '{
    "requestPolicies": {
      "authentication": {
        "type": "JWT_AUTHENTICATION",
        "tokenHeader": "Authorization",
        "tokenAuthScheme": "Bearer",
        "issuers": ["https://identity.oraclecloud.com/"],
        "audiences": ["https://my-api.example.com"],
        "maxClockSkewInSeconds": 30,
        "publicKeys": {
          "type": "REMOTE_JWKS",
          "uri": "https://identity.oraclecloud.com/.well-known/jwks.json",
          "maxCacheDurationInHours": 24,
          "isSslVerifyDisabled": false
        },
        "verifyClaims": [
          {"key": "iss", "values": ["https://identity.oraclecloud.com/"]},
          {"key": "aud", "values": ["https://my-api.example.com"]}
        ]
      }
    },
    "routes": [
      {
        "path": "/users",
        "methods": ["GET"],
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/users"
        }
      },
      {
        "path": "/public/health",
        "methods": ["GET"],
        "requestPolicies": {
          "authentication": {
            "type": "ANONYMOUS"
          }
        },
        "backend": {
          "type": "STOCK_RESPONSE_BACKEND",
          "status": 200,
          "body": "{"status": "healthy"}"
        }
      }
    ]
  }' \
  --wait-for-state ACTIVE

Use JWKS for Key Rotation

Always use the REMOTE_JWKS key type instead of static keys. This allows your identity provider to rotate signing keys without requiring any changes to your API Gateway configuration. The gateway caches the JWKS document and automatically refreshes it when keys change. Set maxCacheDurationInHours to 24 for a good balance between performance and key rotation responsiveness.

Rate Limiting

Rate limiting protects your backend services from being overwhelmed by too many requests. OCI API Gateway supports rate limiting at the deployment level or at the individual route level, with configurable limits based on requests per second. When a client exceeds the rate limit, the gateway returns a 429 Too Many Requests response.

Rate limits can be applied globally (across all clients) or per-client using a key derived from the request, such as the source IP address, a JWT claim, or a custom header value. Per-client rate limiting is more flexible because it prevents a single client from consuming the entire API capacity while allowing other clients to continue normally.

bash
# Deployment with rate limiting
oci api-gateway deployment create \
  --compartment-id $C \
  --gateway-id <gateway-ocid> \
  --display-name "rate-limited-api" \
  --path-prefix "/api/v1" \
  --specification '{
    "requestPolicies": {
      "rateLimiting": {
        "rateInRequestsPerSecond": 100,
        "rateKey": "CLIENT_IP"
      }
    },
    "routes": [
      {
        "path": "/data",
        "methods": ["GET"],
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/data"
        }
      },
      {
        "path": "/bulk-export",
        "methods": ["POST"],
        "requestPolicies": {
          "rateLimiting": {
            "rateInRequestsPerSecond": 5,
            "rateKey": "CLIENT_IP"
          }
        },
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/bulk-export"
        }
      }
    ]
  }' \
  --wait-for-state ACTIVE

# Rate key options:
# CLIENT_IP  - Rate limit per source IP address
# TOTAL      - Global rate limit across all clients

CORS Configuration

Cross-Origin Resource Sharing (CORS) controls which web applications running in browsers can access your API. Without proper CORS configuration, browsers block requests from web pages hosted on a different domain than your API. OCI API Gateway handles CORS automatically, including preflight OPTIONS requests, so your backend services do not need to implement CORS logic.

bash
# Deployment with CORS configuration
oci api-gateway deployment create \
  --compartment-id $C \
  --gateway-id <gateway-ocid> \
  --display-name "cors-enabled-api" \
  --path-prefix "/api/v1" \
  --specification '{
    "requestPolicies": {
      "cors": {
        "allowedOrigins": [
          "https://app.example.com",
          "https://admin.example.com"
        ],
        "allowedMethods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allowedHeaders": [
          "Content-Type",
          "Authorization",
          "X-Request-Id"
        ],
        "exposedHeaders": ["X-Total-Count", "X-Request-Id"],
        "isAllowCredentialsEnabled": true,
        "maxAgeInSeconds": 3600
      }
    },
    "routes": [
      {
        "path": "/resources",
        "methods": ["GET", "POST"],
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/resources"
        }
      }
    ]
  }' \
  --wait-for-state ACTIVE

Request and Response Transformations

OCI API Gateway can modify requests before they reach the backend and responses before they are returned to the client. Transformations are useful for adding or removing headers, renaming query parameters, setting default values, and adapting between different API versions without changing backend code.

Common transformation use cases include adding correlation IDs to all requests, stripping sensitive headers from responses, injecting authentication information for backend services, and converting between API versioning schemes.

bash
# Deployment with request/response transformations
oci api-gateway deployment create \
  --compartment-id $C \
  --gateway-id <gateway-ocid> \
  --display-name "transformed-api" \
  --path-prefix "/api/v1" \
  --specification '{
    "requestPolicies": {
      "headerTransformations": {
        "setHeaders": {
          "items": [
            {"name": "X-Gateway-Version", "values": ["v1"]},
            {"name": "X-Forwarded-Prefix", "values": ["/api/v1"]}
          ]
        },
        "renameHeaders": {
          "items": [
            {"from": "X-Client-Token", "to": "Authorization"}
          ]
        }
      },
      "queryParameterTransformations": {
        "setQueryParameters": {
          "items": [
            {"name": "format", "values": ["json"]}
          ]
        }
      }
    },
    "routes": [
      {
        "path": "/data",
        "methods": ["GET"],
        "backend": {
          "type": "HTTP_BACKEND",
          "url": "http://10.0.1.10:8080/data"
        },
        "responsePolicies": {
          "headerTransformations": {
            "setHeaders": {
              "items": [
                {"name": "X-Content-Type-Options", "values": ["nosniff"]},
                {"name": "X-Frame-Options", "values": ["DENY"]},
                {"name": "Strict-Transport-Security", "values": ["max-age=31536000"]}
              ]
            },
            "removeHeaders": {
              "items": [
                {"name": "Server"},
                {"name": "X-Powered-By"}
              ]
            }
          }
        }
      }
    ]
  }' \
  --wait-for-state ACTIVE

Monitoring and Logging

API Gateway emits metrics to OCI Monitoring and access logs to OCI Logging, providing comprehensive visibility into API traffic patterns, error rates, and latency distribution. Monitoring these metrics is essential for maintaining API health and identifying performance issues.

bash
# Query API call count
oci monitoring metric-data summarize-metrics-data \
  --compartment-id $C \
  --namespace "oci_apigateway" \
  --query-text 'HttpRequests[5m]{resourceId = "<deployment-ocid>"}.sum()'

# Query API latency (p95)
oci monitoring metric-data summarize-metrics-data \
  --compartment-id $C \
  --namespace "oci_apigateway" \
  --query-text 'Latency[5m]{resourceId = "<deployment-ocid>"}.percentile(0.95)'

# Query error rate (4xx and 5xx)
oci monitoring metric-data summarize-metrics-data \
  --compartment-id $C \
  --namespace "oci_apigateway" \
  --query-text 'HttpResponses[5m]{statusCode =~ "4..|5..", resourceId = "<deployment-ocid>"}.sum()'

# Enable execution logging on a deployment
# In the deployment specification, add:
# "loggingPolicies": {
#   "executionLog": {
#     "logLevel": "INFO",
#     "isEnabled": true
#   },
#   "accessLog": {
#     "isEnabled": true
#   }
# }

# Create an alarm for high API error rate
oci monitoring alarm create \
  --compartment-id $C \
  --display-name "api-high-error-rate" \
  --metric-compartment-id $C \
  --namespace "oci_apigateway" \
  --query-text 'HttpResponses[5m]{statusCode =~ "5.."}.sum() > 100' \
  --severity "CRITICAL" \
  --destinations '["<ops-topic-ocid>"]' \
  --is-enabled true \
  --body "API Gateway 5xx errors exceed threshold"

# Delete an API deployment
oci api-gateway deployment delete \
  --deployment-id <deployment-ocid> \
  --force

# Delete an API gateway
oci api-gateway gateway delete \
  --gateway-id <gateway-ocid> \
  --force

Production Best Practices

Deploying APIs in production requires attention to security, reliability, and maintainability. Follow these best practices for OCI API Gateway:

API Versioning: Use path-based versioning (/api/v1/,/api/v2/) with separate deployments per version. This allows you to run multiple API versions simultaneously and deprecate old versions gracefully. The gateway's path-prefix feature maps naturally to versioned APIs.

Security Layers: Combine JWT authentication with rate limiting and WAF integration for defense in depth. Use per-route authentication policies to make specific endpoints public (like health checks) while securing the rest.

Backend Timeouts: Configure appropriate connect, read, and send timeouts for each backend. Set aggressive connect timeouts (5-10 seconds) to fail fast when backends are unreachable, and longer read timeouts (30-60 seconds) for endpoints that perform heavy processing.

Custom Error Responses: Configure custom error responses for authentication failures, rate limit exceeded, and backend errors. This provides a consistent API experience and avoids leaking internal implementation details to API consumers.

Infrastructure as Code: Define gateway configurations in Terraform or OCI Resource Manager for repeatable, version-controlled deployments. The API specification can be stored alongside your application code and deployed as part of your CI/CD pipeline.

OCI Functions Serverless GuideOCI WAF GuideOCI VCN Networking Deep Dive

Key Takeaways

  1. 1API Gateway supports HTTP, Functions, and stock response backends for flexible API architectures.
  2. 2JWT authentication is handled natively by the gateway, eliminating auth code in backends.
  3. 3Rate limiting protects backends from abuse with per-client or global request quotas.
  4. 4Request/response transformations modify headers and parameters without backend code changes.

Frequently Asked Questions

How much does OCI API Gateway cost?
OCI API Gateway charges per API call processed. The first 1 million API calls per month are free. Beyond that, pricing is approximately $3.00 per million API calls. There are no charges for gateway instances, deployments, or idle time. This pay-per-call model makes it very cost-effective for both low and high traffic APIs.
Can API Gateway connect to backends outside OCI?
Yes, API Gateway's HTTP backend type can route requests to any HTTP/HTTPS endpoint, including services running on other cloud providers, on-premises servers, or SaaS APIs. The gateway must have network connectivity to the backend, either through the public internet (for public gateways) or through VPN/FastConnect (for private gateways).

Written by CloudToolStack Team

Cloud engineers and architects with hands-on experience across AWS, Azure, and GCP. We write guides based on real-world production patterns, not just documentation rewrites.

Disclaimer: This guide is for educational purposes. Cloud services change frequently; always refer to official documentation for the latest information. AWS, Azure, and GCP are trademarks of their respective owners.