react-apigee-client
v1.1.0
Published
React client for APIGEE Gateway integration with client credentials authentication
Maintainers
Readme
React APIGEE Client
A React library for easy integration with APIGEE Gateway using client credentials (username/password) authentication.
Note: This SDK ONLY handles APIGEE Gateway proxy calls. SSO authentication is handled separately by your application.
🚀 Features
- ✅ APIGEE Client Credentials Authentication: Automatic token management with username/password
- ✅ Automatic Token Refresh: Handles token expiration and refresh automatically
- ✅ React Hooks: Custom hooks for all API operations
- ✅ TypeScript Support: Full TypeScript support with types
- ✅ Error Handling: Comprehensive error handling and retry logic
- ✅ Environment Variables: Easy configuration from .env files
📦 Installation
npm install react-apigee-client🔧 Quick Start
1. Environment Variables
Create a .env file in your project root:
# APIGEE Gateway URL
REACT_APP_APIGEE_GATEWAY_URL=APIGEE_GATEWAY_URI
# APIGEE Token Endpoint
REACT_APP_APIGEE_TOKEN_ENDPOINT=YOUR_TOKEN_ENDPOINT
# APIGEE Consumer Key (username)
REACT_APP_APIGEE_CONSUMER_KEY=YOUR_CONSUMER_KEY
# APIGEE Consumer Secret (password)
REACT_APP_APIGEE_CONSUMER_SECRET=your_consumer_secret_here
# Optional: Enable Logging
REACT_APP_APIGEE_ENABLE_LOGGING=true2. Setup Provider
import React from 'react';
import { APIGEEProvider, createAPIGEEConfigFromEnv } from 'react-apigee-client';
// Option 1: From environment variables
const config = createAPIGEEConfigFromEnv();
// Option 2: Manual configuration
const config = createAPIGEEConfig({
gatewayUrl: REACT_APP_APIGEE_GATEWAY_URL,
tokenEndpoint: YOUR_TOKEN_ENDPOINT,
consumerKey: process.env.REACT_APP_APIGEE_CONSUMER_KEY,
consumerSecret: process.env.REACT_APP_APIGEE_CONSUMER_SECRET,
enableLogging: true,
});
function App() {
return (
<APIGEEProvider config={config}>
<YourApp />
</APIGEEProvider>
);
}3. Make API Calls
import React from 'react';
import { useAPIGEE, useAPIGEEMutation, useAPIGEEClient } from 'react-apigee-client';
function MyComponent() {
const client = useAPIGEEClient();
// GET request
const { data, loading, error, refetch } = useAPIGEE(
client,
'/your/api/endpoint',
{ page: 1, limit: 10 } // query params
);
// POST request
const { mutate: createItem, loading: creating } = useAPIGEEMutation(client, 'POST', '/your/api/endpoint');
const handleCreate = async () => {
try {
await createItem({ name: 'New Item', value: 100 });
refetch(); // Refresh the list
} catch (error) {
console.error('Failed to create:', error);
}
};
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<button onClick={handleCreate} disabled={creating}>
{creating ? 'Creating...' : 'Create Item'}
</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}🎯 API Reference
Configuration
createAPIGEEConfig({
gatewayUrl: string; // APIGEE Gateway URL
tokenEndpoint: string; // APIGEE Token Endpoint
consumerKey: string; // APIGEE Consumer Key (username)
consumerSecret: string; // APIGEE Consumer Secret (password)
timeout?: number; // Request timeout (default: 30000ms)
enableLogging?: boolean; // Enable logging (default: false)
apiBasePath?: string; // API base path (default: '')
tokenStorageKey?: string; // Token storage key (default: 'apigee_token')
defaultHeaders?: Record<string, string>; // Custom headers
onError?: (error) => void; // Custom error handler
})Hooks
Core API Hooks
// GET request
const { data, loading, error, refetch } = useAPIGEE(client, '/endpoint', params);
// POST request
const { mutate: create, loading, error } = useAPIGEEMutation(client, 'POST', '/endpoint');
// PUT request
const { mutate: update } = useAPIGEEMutation(client, 'PUT', '/endpoint/:id');
// PATCH request
const { mutate: patch } = useAPIGEEMutation(client, 'PATCH', '/endpoint/:id');
// DELETE request
const { mutate: deleteItem } = useAPIGEEMutation(client, 'DELETE', '/endpoint/:id');Direct Client Usage
import { useAPIGEEClient } from 'react-apigee-client';
function MyComponent() {
const client = useAPIGEEClient();
const fetchData = async () => {
try {
const response = await client.get('/your/endpoint', { page: 1 });
console.log(response.data);
} catch (error) {
console.error(error);
}
};
return <button onClick={fetchData}>Fetch Data</button>;
}📝 Examples
Example 1: Basic GET Request
function UsersList() {
const client = useAPIGEEClient();
const { data: users, loading, error } = useAPIGEE(
client,
'/users',
{ page: 1, limit: 10 }
);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<ul>
{users?.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Example 2: POST Request
function CreateUser() {
const client = useAPIGEEClient();
const { mutate: createUser, loading } = useAPIGEEMutation(client, 'POST', '/users');
const handleSubmit = async (formData) => {
try {
await createUser(formData);
alert('User created successfully!');
} catch (error) {
alert('Failed to create user');
}
};
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<button type="submit" disabled={loading}>
{loading ? 'Creating...' : 'Create User'}
</button>
</form>
);
}Example 3: Update and Delete
function UserActions({ userId }) {
const client = useAPIGEEClient();
const { mutate: updateUser } = useAPIGEEMutation(client, 'PUT', `/users/${userId}`);
const { mutate: deleteUser } = useAPIGEEMutation(client, 'DELETE', `/users/${userId}`);
const handleUpdate = async () => {
await updateUser({ name: 'Updated Name' });
};
const handleDelete = async () => {
await deleteUser();
};
return (
<div>
<button onClick={handleUpdate}>Update</button>
<button onClick={handleDelete}>Delete</button>
</div>
);
}🔒 Security
- Client Credentials Flow: Uses OAuth2 client credentials grant (username/password)
- Automatic Token Management: Tokens are refreshed automatically before expiration
- Secure Storage: Tokens are stored securely in localStorage
- Error Handling: Comprehensive error handling and retry logic
🚀 Advanced Usage
Custom Error Handling
const config = createAPIGEEConfig({
gatewayUrl: process.env.REACT_APP_APIGEE_GATEWAY_URL,
tokenEndpoint: process.env.REACT_APP_APIGEE_TOKEN_ENDPOINT,
consumerKey: process.env.REACT_APP_APIGEE_CONSUMER_KEY,
consumerSecret: process.env.REACT_APP_APIGEE_CONSUMER_SECRET,
onError: (error) => {
// Custom error handling
if (error.status === 401) {
console.error('Authentication failed');
} else if (error.status === 429) {
console.error('Rate limit exceeded');
}
}
});Custom Headers
const config = createAPIGEEConfig({
gatewayUrl: process.env.REACT_APP_APIGEE_GATEWAY_URL,
tokenEndpoint: process.env.REACT_APP_APIGEE_TOKEN_ENDPOINT,
consumerKey: process.env.REACT_APP_APIGEE_CONSUMER_KEY,
consumerSecret: process.env.REACT_APP_APIGEE_CONSUMER_SECRET,
defaultHeaders: {
'X-App-Version': '1.0.0',
'X-Client-Type': 'web',
}
});📞 Support
- Documentation: GitHub Wiki
- Issues: GitHub Issues
📝 License
MIT License - see LICENSE file for details.
