API Integration
API integration guide for ZÈYA Admin Panel.
API Configuration
Base URLs
The admin panel uses environment-based API endpoints:
Production:
https://api.zeya.app/api/admin/v1/
Staging:
https://staging-api.zeya.app/api/admin/v1/
Development:
http://localhost:8000/api/admin/v1/
Environment Variables
Configured in .env.local or environment:
NEXT_PUBLIC_API_URL=https://api.zeya.app/api/admin/v1
NEXT_PUBLIC_API_BASE_URL=https://api.zeya.app
API Client Setup
Axios Configuration
import axios from 'axios';
import Cookies from 'js-cookie';
const API_URL = process.env.NEXT_PUBLIC_API_URL;
// Create axios instance
const apiClient = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor for auth token
apiClient.interceptors.request.use(
(config) => {
const token = Cookies.get('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor for error handling
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Handle unauthorized - redirect to login
Cookies.remove('auth_token');
window.location.href = '/authentication/sign-in';
}
return Promise.reject(error);
}
);
Making API Calls
Basic API Call
import axios from 'axios';
import Cookies from 'js-cookie';
const fetchUsers = async () => {
try {
const token = Cookies.get('auth_token');
const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/users`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
};
POST Request
const createUser = async (userData) => {
try {
const token = Cookies.get('auth_token');
const response = await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/admin/create-user`,
userData,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return response.data;
} catch (error) {
throw error;
}
};
PUT/PATCH Request
const updateUser = async (userId, updates) => {
try {
const token = Cookies.get('auth_token');
const response = await axios.patch(
`${process.env.NEXT_PUBLIC_API_URL}/user-update`,
{ ...updates, id: userId },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return response.data;
} catch (error) {
throw error;
}
};
DELETE Request
const deleteUser = async (userId) => {
try {
const token = Cookies.get('auth_token');
const response = await axios.delete(
`${process.env.NEXT_PUBLIC_API_URL}/user/${userId}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return response.data;
} catch (error) {
throw error;
}
};
Authentication
Login
const login = async (email, password) => {
try {
const response = await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/login`,
{ email, password }
);
// Store token in cookie
if (response.data.data?.token) {
Cookies.set('auth_token', response.data.data.token, { expires: 7 });
}
return response.data;
} catch (error) {
throw error;
}
};
Logout
const logout = async () => {
try {
const token = Cookies.get('auth_token');
await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/logout`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// Remove token
Cookies.remove('auth_token');
} catch (error) {
// Remove token even if API call fails
Cookies.remove('auth_token');
}
};
Check Token
const checkToken = async () => {
try {
const token = Cookies.get('auth_token');
if (!token) return false;
const response = await axios.get(
`${process.env.NEXT_PUBLIC_API_URL}/check-token`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
return response.data.success;
} catch (error) {
return false;
}
};
Error Handling
API Error Structure
{
success: false,
error: "Error message",
code: "ERROR_CODE",
errors: { ... } // For validation errors
}
Handling Errors
try {
const data = await fetchUsers();
} catch (error) {
if (error.response) {
// Server responded with error
const { error: errorMessage, code, errors } = error.response.data;
if (code === 'VALIDATION_ERROR') {
// Handle validation errors
console.log('Validation errors:', errors);
} else if (error.response.status === 401) {
// Handle unauthorized
router.push('/authentication/sign-in');
} else {
// Handle other errors
alert(errorMessage);
}
} else if (error.request) {
// Request made but no response
alert('Network Error: Please check your internet connection');
} else {
// Something else happened
alert('An unexpected error occurred');
}
}
Response Format
Success Response
{
"success": true,
"data": { ... },
"message": "Operation successful"
}
Paginated Response
{
"success": true,
"data": [ ... ],
"pagination": {
"current_page": 1,
"total_pages": 5,
"total_items": 100,
"per_page": 20
}
}
Common API Endpoints
Users
// List users
GET /users
// Get user details
GET /user-profile
// Create user
POST /admin/create-user
// Update user
PATCH /user-update
// Delete user
DELETE /user/{id}
// Export users
GET /users-export
Products
// List products
GET /products
// Get product details
GET /products/{id}
// Update product
PATCH /product-update
// Delete product
DELETE /product/{id}
// Product verification
GET /add-product-verification
POST /mark-product-verified/{id}
Reports
// Transaction report
GET /report/transaction
// User report
GET /report/user/{id}
// Subscription report
GET /report/subscription
// Reported products
GET /report/reported-product/all
Analytics & Insights
// User analytics
GET /insight/active-inactive-accounts
GET /insight/daily-active-users
// Swap analytics
GET /insight/total-swap-requests-sent
GET /insight/total-successful-swaps
// Engagement metrics
GET /insight/engagement-overview
Data Caching
Using Caching Hook
import useCachedData from '../hooks/useCachedData';
function UsersList() {
const { data, loading, error, refetch } = useCachedData(
'users-list',
async () => {
const response = await fetchUsers();
return response.data;
},
{ ttl: 60000 } // Cache for 60 seconds
);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{data.map(user => <div key={user.id}>{user.name}</div>)}
<button onClick={refetch}>Refresh</button>
</div>
);
}
Manual Caching
import dataCache from '../utils/dataCache';
// Cache data
dataCache.set('key', data, 60000); // Cache for 60 seconds
// Get cached data
const cachedData = dataCache.get('key');
// Clear cache
dataCache.clear('key');
Testing API Integration
Mock API Responses
// For development/testing
const mockUsers = [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
];
// Use in development
const users = process.env.NEXT_PUBLIC_APP_ENV === 'development'
? mockUsers
: await fetchUsers();
Network Debugging
- Use browser DevTools Network tab
- Check request/response headers
- Verify authentication tokens
- Monitor API response times