API Service Call
Utilities for making authenticated API requests to AuthScape backends.
The apiService utility provides methods for making authenticated HTTP requests to AuthScape API endpoints.
Features
- Automatic token handling
- Request/response interceptors
- Error handling
- All HTTP methods supported
- TypeScript support
Import
javascript
import { apiService } from 'authscape';
Response Structure
All API responses return an Axios response object with:
response.status- HTTP status code (200, 201, 400, etc.)response.data- The actual data returned from the server
Always check the status and access data through response.data:
javascript
let response = await apiService().get("/Users/GetAll");if (response != null && response.status == 200) {// Access the dataconst users = response.data;console.log(users);}
Methods
GET Request
javascript
// Simple GETlet response = await apiService().get("/Users/GetAll");if (response != null && response.status == 200) {const users = response.data;setUsers(users);}// GET with query parameterslet response = await apiService().get("/Users/GetUser?id=123");if (response != null && response.status == 200) {const user = response.data;setUser(user);}
POST Request
javascript
let response = await apiService().post("/Users/Create", {firstName: "John",lastName: "Doe",email: "john@example.com"});if (response != null && response.status == 200) {const newUser = response.data;console.log("Created user:", newUser.id);}
PUT Request
javascript
let response = await apiService().put("/Users/Update", {id: 123,firstName: "John",lastName: "Doe"});if (response != null && response.status == 200) {notification("User updated successfully");}
DELETE Request
javascript
let response = await apiService().delete("/Users/Delete?id=123");if (response != null && response.status == 200) {notification("User deleted");refreshList();}
Paginated Data
For endpoints that return paginated data, the response typically includes data and recordsTotal:
javascript
const [items, setItems] = useState([]);const [rowCount, setRowCount] = useState(0);const paginationModel = {offset: 0,length: 25,sortBy: "createdAt",sortDirection: "desc"};let response = await apiService().post("/ContentManagement/GetPageAssets", paginationModel);if (response != null && response.status == 200) {setItems(response.data.data); // The array of itemssetRowCount(response.data.recordsTotal); // Total count for pagination}
Complete Examples
Loading Data into State
javascript
import { useState, useEffect } from 'react';import { apiService } from 'authscape';function UserList() {const [users, setUsers] = useState([]);const [loading, setLoading] = useState(true);useEffect(() => {loadUsers();}, []);const loadUsers = async () => {setLoading(true);let response = await apiService().get("/Users/GetAll");if (response != null && response.status == 200) {setUsers(response.data);}setLoading(false);};if (loading) return <div>Loading...</div>;return (<ul>{users.map(user => (<li key={user.id}>{user.firstName} {user.lastName}</li>))}</ul>);}
DataGrid with Pagination
javascript
import { useState, useEffect } from 'react';import { apiService } from 'authscape';import { DataGrid } from '@mui/x-data-grid';function AssetList() {const [assets, setAssets] = useState([]);const [rowCount, setRowCount] = useState(0);const [paginationModel, setPaginationModel] = useState({page: 0,pageSize: 25});useEffect(() => {loadAssets();}, [paginationModel]);const loadAssets = async () => {let response = await apiService().post("/ContentManagement/GetPageAssets", {offset: paginationModel.page * paginationModel.pageSize,length: paginationModel.pageSize});if (response != null && response.status == 200) {setAssets(response.data.data);setRowCount(response.data.recordsTotal);}};const columns = [{ field: 'id', headerName: 'ID', width: 90 },{ field: 'name', headerName: 'Name', width: 200 },{ field: 'type', headerName: 'Type', width: 150 }];return (<DataGridrows={assets}columns={columns}rowCount={rowCount}paginationModel={paginationModel}onPaginationModelChange={setPaginationModel}paginationMode="server"pageSizeOptions={[10, 25, 50]}/>);}
Create and Refresh
javascript
const handleCreate = async (formData) => {let response = await apiService().post("/Products/Create", {name: formData.name,price: formData.price,description: formData.description});if (response != null && response.status == 200) {notification("Product created successfully");// Refresh the listawait loadProducts();// Or access the new itemconst newProduct = response.data;console.log("New product ID:", newProduct.id);}};
Update with Confirmation
javascript
const handleUpdate = async (id, updates) => {let response = await apiService().put("/Products/Update", {id: id,...updates});if (response != null && response.status == 200) {notification("Product updated");// Update local statesetProducts(prev => prev.map(p =>p.id === id ? { ...p, ...updates } : p));}};
Delete with Confirmation
javascript
const handleDelete = async (id) => {if (!confirm("Are you sure you want to delete this item?")) {return;}let response = await apiService().delete(`/Products/Delete?id=${id}`);if (response != null && response.status == 200) {notification("Product deleted");// Remove from local statesetProducts(prev => prev.filter(p => p.id !== id));}};
File Upload
javascript
const handleFileUpload = async (file) => {const formData = new FormData();formData.append('file', file);let response = await apiService().post('/Documents/Upload', formData, {headers: { 'Content-Type': 'multipart/form-data' }});if (response != null && response.status == 200) {const uploadedFile = response.data;console.log("File URL:", uploadedFile.uri);return uploadedFile;}};
Error Handling
javascript
import { apiService, authService } from 'authscape';const loadData = async () => {try {let response = await apiService().get('/api/Data');if (response != null && response.status == 200) {return response.data;}} catch (error) {if (error.response) {switch (error.response.status) {case 401:// Token expired, redirect to loginauthService().login(window.location.href);break;case 403:notification("You do not have permission to access this resource");break;case 404:notification("Resource not found");break;case 500:notification("Server error. Please try again later.");break;default:notification(error.response.data?.message || "An error occurred");}} else {notification("Network error. Please check your connection.");}}};
Configuration
The apiService automatically:
- Adds the
Authorization: Bearer {token}header - Sets
Content-Type: application/jsonfor JSON requests - Uses the base URL from environment configuration
- Handles token refresh when expired
Best Practices
- Always check status - Verify
response.status == 200before using data - Access data correctly - Use
response.datato get the actual data - Handle null responses - Check
response != nullbefore accessing properties - Show loading states - Indicate when requests are in progress
- Handle errors - Wrap API calls in try/catch for error handling