STCMS Documentation
Complete guide to building modern, secure React/PHP applications with STCMS framework
API Integration
Complete guide to integrating APIs with STCMS
Using ApiClient
PHP Backend
use Gemvc\Stcms\Core\ApiClient;
$apiClient = new ApiClient($_ENV['API_BASE_URL']);
// GET request
$users = $apiClient->get('/users', ['page' => 1]);
// POST request with JWT
$response = $apiClient->post('/users', [
'name' => 'John Doe',
'email' => 'john@example.com'
], $jwt);
// PUT request
$updated = $apiClient->put('/users/123', [
'name' => 'Jane Doe'
], $jwt);
// DELETE request
$deleted = $apiClient->delete('/users/123', $jwt);
Use the ApiClient class for all HTTP requests to external APIs with built-in JWT support.
React API Calls
Frontend API Integration
import React, { useState, useEffect } from 'react';
export default function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const jwt = document.getElementById('user-list-root').dataset.jwt;
fetch('/api/users', {
headers: {
'Authorization': `Bearer ${jwt}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
setUsers(data);
setLoading(false);
});
}, []);
if (loading) return <div>Loading users...</div>;
return (
<div>
{users.map(user => (
<div key={user.id} className="p-4 border rounded mb-2">
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
))}
</div>
);
}
React components can make API calls using the JWT token passed from the server.
Error Handling
PHP Error Handling
try {
$users = $apiClient->get('/users', ['page' => 1]);
// Process successful response
} catch (\Exception $e) {
// Handle API errors
error_log('API Error: ' . $e->getMessage());
$users = []; // Fallback data
}
Always wrap API calls in try-catch blocks to handle errors gracefully.
Caching API Responses
Using Symfony Cache
use Symfony\Component\Cache\Adapter\ApcuAdapter;
$cache = new ApcuAdapter();
$cacheKey = 'users_page_' . $page;
// Try to get from cache first
$users = $cache->get($cacheKey, function() use ($apiClient, $page) {
return $apiClient->get('/users', ['page' => $page]);
});
Cache API responses to improve performance and reduce API calls.
API Authentication
JWT Authentication
// JWT is automatically included in API requests
$apiClient = new ApiClient($_ENV['API_BASE_URL']);
// The JWT is passed from the session
$response = $apiClient->get('/user/profile', $jwt);
// For React components, JWT is passed via data attributes
// <div id="user-profile" data-jwt=""></div>
JWT tokens are automatically handled by the ApiClient for authenticated requests.
API Integration Best Practices
- • Always handle errors and provide fallback data
- • Cache responses to improve performance
- • Use environment variables for API endpoints
- • Validate responses before using data
- • Implement rate limiting for external APIs
- • Log API errors for debugging
- • Use HTTPS for all API communications