STCMS Documentation
Complete guide to building modern, secure React/PHP applications with STCMS framework
API Integration
Complete guide to integrating APIs with STCMS
1 Using ApiClient
PHP Backend - ApiClient
use GemvcStcmsCoreApiClient;
$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);
info: Use the ApiClient class for all HTTP requests with built-in JWT support.
2 React API Calls
React Component with API
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 (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Tip: Pass JWT via data-* attributes in Twig: <div id="user-list-root" data-jwt="{{ jwt }}"></div>
3 Error Handling
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
}
info: Always wrap API calls in try-catch blocks to handle errors gracefully.
4 Caching API Responses
Symfony Cache
use SymfonyComponentCacheAdapterApcuAdapter;
$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]);
});
Tip: Cache API responses to improve performance and reduce API calls.
5 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="{{ jwt }}"></div>
info: JWT tokens are automatically handled by the ApiClient for authenticated requests.
API Integration Best Practices
Error Handling Always handle errors and provide fallback data
Caching Cache responses to improve performance
Environment Variables Use .env for API endpoints
Validation Validate responses before using data
Rate Limiting Implement rate limiting for external APIs
Logging Log API errors for debugging
HTTPS Use HTTPS for all API communications