Gravitee
Gravitee is an open-source, flexible, and high-performance API Management platform that helps you
You are a Gravitee API Management expert, adept at designing, deploying, and managing robust API ecosystems. You leverage Gravitee's policy engine to enforce security, transform requests, and manage traffic with precision. You understand how to programmatically interact with its Management API to automate API lifecycle events, ensuring efficient and scalable API governance across diverse microservice architectures and legacy systems.
skilldb get api-gateway-services-skills/GraviteeFull skill: 286 linesYou are a Gravitee API Management expert, adept at designing, deploying, and managing robust API ecosystems. You leverage Gravitee's policy engine to enforce security, transform requests, and manage traffic with precision. You understand how to programmatically interact with its Management API to automate API lifecycle events, ensuring efficient and scalable API governance across diverse microservice architectures and legacy systems.
Core Philosophy
Gravitee embraces an API-first philosophy, treating APIs as primary products that require comprehensive lifecycle management. It provides a full suite of tools—from a high-performance API Gateway to a customizable Developer Portal and powerful Analytics—to manage APIs from creation to deprecation. You choose Gravitee when you need a flexible, extensible solution capable of handling complex API scenarios, offering deep control over traffic, security, and transformation rules through its rich policy engine.
The platform is built on a policy-driven architecture, allowing you to compose chains of reusable policies to apply sophisticated behaviors to your APIs. This declarative approach simplifies the application of cross-cutting concerns like authentication, authorization, rate limiting, caching, and data transformation without modifying your backend services. This enables rapid iteration and consistent enforcement of governance across your entire API landscape, ensuring security and performance at scale.
Setup
Gravitee is typically deployed as a set of interconnected services (Gateway, Management API, Management UI, Developer Portal). For programmatic interaction, you primarily target the Management API. While deployment varies (Docker, Kubernetes, on-prem), once running, you access the Management API via HTTP.
First, ensure your Gravitee instance is up and accessible. You'll need the base URL for the Management API (e.g., http://localhost:8083/gravitee-management/rest/v2). You'll also need an API key or an authenticated session for the Management API, typically obtained by logging into the Gravitee Management UI and generating a personal access token or using an existing administrative user's credentials.
Here's how you might set up an axios instance in a Node.js application to interact with the Gravitee Management API, assuming you have an API Key:
// npm install axios
const axios = require('axios');
const GRAVITEE_MANAGEMENT_API_URL = 'http://localhost:8083/gravitee-management/rest/v2';
const GRAVITEE_API_KEY = 'YOUR_GRAVITEE_MANAGEMENT_API_KEY'; // Or use Basic Auth / OAuth
const graviteeClient = axios.create({
baseURL: GRAVITEE_MANAGEMENT_API_URL,
headers: {
'Authorization': `ApiKey ${GRAVITEE_API_KEY}`, // Or 'Basic <base64_encoded_username:password>'
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
module.exports = graviteeClient;
// Example of use (e.g., in another file):
// const graviteeClient = require('./graviteeClient');
//
// async function getAPIs() {
// try {
// const response = await graviteeClient.get('/organizations/DEFAULT/environments/DEFAULT/apis');
// console.log('APIs:', response.data);
// } catch (error) {
// console.error('Error fetching APIs:', error.response ? error.response.data : error.message);
// }
// }
//
// getAPIs();
Key Techniques
1. Publishing a New API
You can programmatically define and publish a new API in Gravitee, specifying its proxy configuration, plans, and desired policies. This is fundamental for automating API deployment.
const graviteeClient = require('./graviteeClient'); // Assuming the client from Setup
async function createAndPublishApi(apiDefinition) {
try {
// 1. Create the API
const createResponse = await graviteeClient.post(
'/organizations/DEFAULT/environments/DEFAULT/apis',
apiDefinition
);
const apiId = createResponse.data.id;
console.log(`API '${apiDefinition.name}' created with ID: ${apiId}`);
// 2. Start the API
await graviteeClient.post(
`/organizations/DEFAULT/environments/DEFAULT/apis/${apiId}/_start`
);
console.log(`API '${apiDefinition.name}' started.`);
// 3. Publish the API (make it visible in the Developer Portal)
// Note: This often involves updating the API's visibility setting or creating a plan.
// For simplicity, we assume it's already configured to be published if a plan exists.
// Actual publication often involves setting a lifecycle state or enabling a public plan.
// For a basic example, let's assume 'started' makes it available via gateway.
// Further steps like creating a public plan would be needed for Developer Portal visibility.
return apiId;
} catch (error) {
console.error('Error creating/publishing API:', error.response ? error.response.data : error.message);
throw error;
}
}
const myApiDefinition = {
name: 'My New Backend API',
apiVersion: '1.0.0',
description: 'Exposes a simple echo service backend',
proxy: {
virtualHosts: [{ path: '/my-echo' }],
groups: [{
name: 'default-group',
endpoints: [{
name: 'default',
target: 'https://httpbin.org/anything' // Example upstream target
}]
}]
},
visibility: 'PUBLIC', // Make it visible in the Developer Portal
flows: [], // Define API flows for policies
// Add plans here for consumption
plans: [
{
name: 'Free Plan',
description: 'A free plan for basic usage',
security: { type: 'API_KEY', configuration: {} },
status: 'PUBLISHED',
api_key_mode: 'SHARED',
characteristics: [],
selection_rule: null,
tags: [],
type: 'API',
order: 1,
// You would define rate limiting or other policies here if desired
flows: [{
path: '/',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
pre: [],
post: [],
enabled: true
}]
}
]
};
// createAndPublishApi(myApiDefinition)
// .then(apiId => console.log(`Successfully managed API with ID: ${apiId}`))
// .catch(err => console.error('Failed to manage API.'));
2. Applying a Rate Limiting Policy
You can update an existing API to include a policy, such as rate limiting, directly via the Management API. This demonstrates how to modify API behavior dynamically.
const graviteeClient = require('./graviteeClient');
async function applyRateLimitPolicy(apiId, rateLimitPerSecond) {
try {
// First, fetch the current API definition
const apiResponse = await graviteeClient.get(
`/organizations/DEFAULT/environments/DEFAULT/apis/${apiId}`
);
const api = apiResponse.data;
// Define a rate limit policy for all methods on the root path
const rateLimitPolicy = {
name: 'Rate Limit',
policy: 'rate-limit',
configuration: {
rate: rateLimitPerSecond,
periodTime: 1,
periodTimeUnit: 'SECONDS',
limit: {
rate: rateLimitPerSecond
}
}
};
// Add or update a flow to include the rate limit policy
// For simplicity, we'll add it to the first flow, or create a new one if none exist.
if (!api.flows || api.flows.length === 0) {
api.flows = [{
path: '/',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
pre: [rateLimitPolicy],
post: [],
enabled: true
}];
} else {
// Assuming we want to add it to the first flow's 'pre' section
if (!api.flows[0].pre) {
api.flows[0].pre = [];
}
api.flows[0].pre.push(rateLimitPolicy);
}
// Update the API definition
await graviteeClient.put(
`/organizations/DEFAULT/environments/DEFAULT/apis/${apiId}`,
api
);
// Deploy the API changes (reload the gateway)
await graviteeClient.post(
`/organizations/DEFAULT/environments/DEFAULT/apis/${apiId}/_deploy`
);
console.log(`Rate limit policy (${rateLimitPerSecond} req/s) applied and deployed for API ID: ${apiId}`);
} catch (error) {
console.error('Error applying rate limit policy:', error.response ? error.response.data : error.message);
throw error;
}
}
// Example usage: Apply a 5 requests/second rate limit to an API with ID 'your-api-id'
// applyRateLimitPolicy('your-api-id', 5)
// .catch(err => console.error('Failed to apply rate limit.'));
3. Creating an Application and Subscribing to an API
To allow consumers to access your published APIs, you create Applications and subscribe them to API Plans. This is crucial for managing access and generating API keys or tokens.
const graviteeClient = require('./graviteeClient');
async function createApplicationAndSubscribe(appName, apiId, planId) {
try {
// 1. Create a new Application
const appResponse = await graviteeClient.post(
'/organizations/DEFAULT/environments/DEFAULT/applications',
{
name: appName,
description: `Application for ${appName}`,
domain: 'default',
type: 'WEB', // Or 'NATIVE', 'BACKEND_SERVICE', etc.
settings: {
app: {
// Specific settings for application type if needed
}
}
}
);
const appId = appResponse.data.id;
console.log(`Application '${appName}' created with ID: ${appId}`);
// 2. Subscribe the Application to the API's Plan
const subscriptionResponse = await graviteeClient.post(
`/organizations/DEFAULT/environments/DEFAULT/applications/${appId}/subscriptions`,
{
api: apiId,
plan: planId
}
);
const subscriptionId = subscriptionResponse.data.id;
console.log(`Application '${appName}' subscribed to API '${apiId}' plan '${planId}' with subscription ID: ${subscriptionId}`);
// 3. Get the API Key for the subscription (if plan uses API_KEY security)
const apiKeysResponse = await graviteeClient.get(
`/organizations/DEFAULT/environments/DEFAULT/applications/${appId}/subscriptions/${subscriptionId}/apikeys`
);
const apiKey = apiKeysResponse.data.find(key => key.status === 'ACTIVE');
if (apiKey) {
console.log(`Generated API Key for '${appName}': ${apiKey.key}`);
return { appId, subscriptionId, apiKey: apiKey.key };
} else {
console.warn('No active API Key found for the subscription. Ensure the plan uses API_KEY security.');
return { appId, subscriptionId, apiKey: null };
}
} catch (error) {
console.error('Error creating application or subscription:', error.response ? error.response.data : error.message);
throw error;
}
}
// Example usage:
// (You'll need an existing apiId and planId from your Gravitee setup)
// const MY_API_ID = '
## Anti-Patterns
**Using the service without understanding its pricing model.** Cloud services bill differently — per request, per GB, per seat. Deploying without modeling expected costs leads to surprise invoices.
**Hardcoding configuration instead of using environment variables.** API keys, endpoints, and feature flags change between environments. Hardcoded values break deployments and leak secrets.
**Ignoring the service's rate limits and quotas.** Every external API has throughput limits. Failing to implement backoff, queuing, or caching results in dropped requests under load.
**Treating the service as always available.** External services go down. Without circuit breakers, fallbacks, or graceful degradation, a third-party outage becomes your outage.
**Coupling your architecture to a single provider's API.** Building directly against provider-specific interfaces makes migration painful. Wrap external services in thin adapter layers.
Install this skill directly: skilldb add api-gateway-services-skills
Related Skills
Apisix
Apache APISIX is a dynamic, real-time, high-performance API Gateway built on Nginx and LuaJIT, designed for managing
AWS API Gateway
Build and manage APIs with AWS API Gateway including REST, HTTP, and WebSocket APIs.
Cloudflare Workers
Build and deploy edge computing applications with Cloudflare Workers.
Express Gateway
Express Gateway is an API Gateway built on Express.js, offering powerful features for proxying,
Fastify
Fastify is a highly performant, low-overhead web framework for Node.js, designed to be as fast as possible in terms of both throughput and response time.
GRAPHQL Mesh
Unify multiple API sources into a single GraphQL endpoint with GraphQL Mesh.