Users API
The Users API provides comprehensive user management, search, statistics, and administrative features for managing user data and accounts.
All endpoints use the base URL: https://jethings-backend.fly.dev (production) or http://localhost:3000 (development)
π Authentication & Authorization
All Users API endpoints require authentication via Bearer token in the Authorization header.
Required Headers:
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
Role Requirements:
- User endpoints: Any authenticated user
- Admin endpoints:
admin or super_admin role required
- Super Admin endpoints:
super_admin role required
π€ User Profile Management
Get Current User
Retrieve the current authenticated userβs profile information.
curl -X GET https://jethings-backend.fly.dev/users/me \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Success Response (200):
{
"id": "ck_123...",
"email": "jane@example.com",
"firstName": "Jane",
"lastName": "Doe",
"age": 28,
"phoneNumber": "+1234567890",
"avatarUrl": "https://example.com/avatar.jpg",
"description": "Software developer",
"roles": ["user"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": "2024-01-15T10:30:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}
Update Current User
Update the current userβs profile information.
curl -X PUT https://jethings-backend.fly.dev/users/me \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"firstName": "Jane",
"lastName": "Smith",
"age": 29,
"phoneNumber": "+1234567891",
"avatarUrl": "https://example.com/new-avatar.jpg",
"description": "Updated description"
}'
Request Body:
| Field | Type | Required | Description |
firstName | string | β | Userβs first name |
lastName | string | β | Userβs last name |
age | number | β | Integer between 1-120 |
phoneNumber | string | β | Valid phone number (must be unique) |
avatarUrl | string | β | URL to userβs avatar image |
description | string | β | Userβs bio/description |
Users can only update their own profile fields. Admin-only fields (roles, isEmailVerified, isActive) are ignored.
Success Response (200):
{
"id": "ck_123...",
"email": "jane@example.com",
"firstName": "Jane",
"lastName": "Smith",
"age": 29,
"phoneNumber": "+1234567891",
"avatarUrl": "https://example.com/new-avatar.jpg",
"description": "Updated description",
"roles": ["user"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": "2024-01-15T10:30:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T11:00:00.000Z"
}
Error Responses:
409 Conflict: Email already in use
409 Conflict: Phone number already in use
π User Search & Management (Admin Only)
Get Users
Retrieve a paginated list of users with advanced filtering and search capabilities.
curl -X GET "https://jethings-backend.fly.dev/users?page=1&limit=10&search=jane&isActive=true" \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Query Parameters:
| Parameter | Type | Required | Description |
search | string | β | Search across firstName, lastName, email, phoneNumber |
firstName | string | β | Filter by first name (partial match) |
lastName | string | β | Filter by last name (partial match) |
email | string | β | Filter by email (partial match) |
phoneNumber | string | β | Filter by phone number (partial match) |
roles | string[] | β | Filter by roles (exact match) |
isEmailVerified | boolean | β | Filter by email verification status |
isActive | boolean | β | Filter by account status |
page | number | β | Page number (default: 1) |
limit | number | β | Items per page (default: 10, max: 100) |
sortBy | string | β | Sort field (default: βcreatedAtβ) |
sortOrder | string | β | Sort order: βascβ or βdescβ (default: βdescβ) |
Success Response (200):
{
"users": [
{
"id": "ck_123...",
"email": "jane@example.com",
"firstName": "Jane",
"lastName": "Doe",
"age": 28,
"phoneNumber": "+1234567890",
"avatarUrl": "https://example.com/avatar.jpg",
"description": "Software developer",
"roles": ["user"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": "2024-01-15T10:30:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 25,
"totalPages": 3,
"hasNext": true,
"hasPrev": false
}
}
Get User Statistics
Retrieve user statistics and analytics.
curl -X GET https://jethings-backend.fly.dev/users/stats \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Success Response (200):
{
"totalUsers": 150,
"activeUsers": 142,
"verifiedUsers": 135,
"usersByRole": {
"user": 140,
"admin": 8,
"super_admin": 2
}
}
Get User by ID
Retrieve a specific userβs information by their ID.
curl -X GET https://jethings-backend.fly.dev/users/ck_123... \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Path Parameters:
id (string): User ID (UUID format)
Success Response (200):
{
"id": "ck_123...",
"email": "jane@example.com",
"firstName": "Jane",
"lastName": "Doe",
"age": 28,
"phoneNumber": "+1234567890",
"avatarUrl": "https://example.com/avatar.jpg",
"description": "Software developer",
"roles": ["user"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": "2024-01-15T10:30:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}
Error Responses:
404 Not Found: User not found
Update User (Admin Only)
Update any userβs information with admin privileges.
curl -X PUT https://jethings-backend.fly.dev/users/ck_123... \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"firstName": "Jane",
"lastName": "Smith",
"email": "jane.smith@example.com",
"phoneNumber": "+1234567891",
"age": 29,
"avatarUrl": "https://example.com/avatar.jpg",
"description": "Updated description",
"roles": ["admin"],
"isEmailVerified": true,
"isActive": true
}'
Request Body:
| Field | Type | Required | Description |
firstName | string | β | Userβs first name |
lastName | string | β | Userβs last name |
email | string | β | Valid email address (must be unique) |
phoneNumber | string | β | Valid phone number (must be unique) |
age | number | β | Integer between 1-120 |
avatarUrl | string | β | URL to userβs avatar image |
description | string | β | Userβs bio/description |
roles | string[] | β | User roles (admin only) |
isEmailVerified | boolean | β | Email verification status (admin only) |
isActive | boolean | β | Account status (admin only) |
Success Response (200):
{
"id": "ck_123...",
"email": "jane.smith@example.com",
"firstName": "Jane",
"lastName": "Smith",
"age": 29,
"phoneNumber": "+1234567891",
"avatarUrl": "https://example.com/avatar.jpg",
"description": "Updated description",
"roles": ["admin"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": "2024-01-15T10:30:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T11:00:00.000Z"
}
Error Responses:
404 Not Found: User not found
409 Conflict: Email already in use
409 Conflict: Phone number already in use
π Account Management (Admin Only)
Deactivate User
Deactivate a user account (soft delete).
curl -X POST https://jethings-backend.fly.dev/users/ck_123.../deactivate \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Success Response (200):
{
"message": "User deactivated successfully"
}
Error Responses:
404 Not Found: User not found
Activate User
Reactivate a previously deactivated user account.
curl -X POST https://jethings-backend.fly.dev/users/ck_123.../activate \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Success Response (200):
{
"message": "User activated successfully"
}
Error Responses:
404 Not Found: User not found
Delete User
Permanently delete a user and all associated data.
This action cannot be undone. All user data will be permanently deleted.
curl -X DELETE https://jethings-backend.fly.dev/users/ck_123... \
-H "Authorization: Bearer YOUR_ADMIN_TOKEN"
Success Response (200):
{
"message": "User deleted successfully"
}
Error Responses:
404 Not Found: User not found
π Super Admin Management
Get All Admins
Retrieve all admin users (admin and super_admin roles).
curl -X GET https://jethings-backend.fly.dev/users/admins \
-H "Authorization: Bearer YOUR_SUPER_ADMIN_TOKEN"
Success Response (200):
[
{
"id": "ck_123...",
"email": "admin@example.com",
"firstName": "John",
"lastName": "Admin",
"age": 35,
"phoneNumber": "+1234567890",
"avatarUrl": "https://example.com/avatar.jpg",
"description": "System administrator",
"roles": ["admin"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": "2024-01-15T10:30:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z",
"isAdmin": true,
"isSuperAdmin": false
}
]
Create Admin
Create a new admin user account.
curl -X POST https://jethings-backend.fly.dev/users/admins \
-H "Authorization: Bearer YOUR_SUPER_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"firstName": "Jane",
"lastName": "Admin",
"email": "jane.admin@example.com",
"password": "securePassword123",
"phoneNumber": "+1234567891",
"age": 30,
"description": "New system administrator",
"roles": ["admin"]
}'
Request Body:
| Field | Type | Required | Description |
firstName | string | β
| Adminβs first name |
lastName | string | β
| Adminβs last name |
email | string | β
| Valid email address (must be unique) |
password | string | β
| Minimum 6 characters |
phoneNumber | string | β
| Valid phone number (must be unique) |
age | number | β
| Integer between 1-120 |
description | string | β | Optional description |
roles | string[] | β | User roles (default: [βadminβ]) |
Success Response (200):
{
"message": "Admin created successfully",
"admin": {
"id": "ck_456...",
"email": "jane.admin@example.com",
"firstName": "Jane",
"lastName": "Admin",
"age": 30,
"phoneNumber": "+1234567891",
"avatarUrl": null,
"description": "New system administrator",
"roles": ["admin"],
"isEmailVerified": true,
"isActive": true,
"lastActivity": null,
"createdAt": "2024-01-15T12:00:00.000Z",
"updatedAt": "2024-01-15T12:00:00.000Z",
"isAdmin": true,
"isSuperAdmin": false
}
}
Error Responses:
409 Conflict: Email already in use
409 Conflict: Phone number already in use
Delete Admin
Delete an admin user account.
curl -X DELETE https://jethings-backend.fly.dev/users/admins/ck_123... \
-H "Authorization: Bearer YOUR_SUPER_ADMIN_TOKEN"
Success Response (200):
{
"message": "Admin deleted successfully"
}
Error Responses:
404 Not Found: Admin not found
400 Bad Request: User is not an admin
400 Bad Request: Cannot delete super admin
Block Admin
Block an admin user account.
curl -X POST https://jethings-backend.fly.dev/users/admins/ck_123.../block \
-H "Authorization: Bearer YOUR_SUPER_ADMIN_TOKEN"
Success Response (200):
{
"message": "Admin blocked successfully"
}
Error Responses:
404 Not Found: Admin not found
400 Bad Request: User is not an admin
400 Bad Request: Cannot block super admin
Unblock Admin
Unblock a previously blocked admin user account.
curl -X POST https://jethings-backend.fly.dev/users/admins/ck_123.../unblock \
-H "Authorization: Bearer YOUR_SUPER_ADMIN_TOKEN"
Success Response (200):
{
"message": "Admin unblocked successfully"
}
Error Responses:
404 Not Found: Admin not found
400 Bad Request: User is not an admin
π§ Error Handling
Common Error Codes
| Status Code | Description | Common Causes |
400 Bad Request | Invalid request data | Validation errors, malformed JSON |
401 Unauthorized | Authentication required | Missing/invalid token, expired token |
403 Forbidden | Insufficient permissions | Wrong role, not admin/super_admin |
404 Not Found | Resource not found | Invalid user ID, user doesnβt exist |
409 Conflict | Resource conflict | Email/phone already exists |
500 Internal Server Error | Server error | Database issues, unexpected errors |
{
"message": "Error description",
"statusCode": 400
}
Handling Errors in Your Code
try {
const response = await fetch('https://jethings-backend.fly.dev/users', {
headers: {
'Authorization': `Bearer ${adminToken}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Failed to fetch users');
}
const data = await response.json();
// Handle success
} catch (error) {
console.error('Users API error:', error.message);
// Handle error
}
π Frontend Integration Examples
TypeScript Service Class
class UserService {
private baseUrl = 'https://jethings-backend.fly.dev';
private accessToken: string;
constructor(accessToken: string) {
this.accessToken = accessToken;
}
async getUsers(filters: any = {}) {
const params = new URLSearchParams();
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
if (Array.isArray(value)) {
value.forEach(v => params.append(`${key}[]`, v));
} else {
params.append(key, String(value));
}
}
});
const response = await fetch(`${this.baseUrl}/users?${params}`, {
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`Failed to fetch users: ${response.statusText}`);
}
return response.json();
}
async updateUser(userId: string, data: any) {
const response = await fetch(`${this.baseUrl}/users/${userId}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`Failed to update user: ${response.statusText}`);
}
return response.json();
}
async deleteUser(userId: string) {
const response = await fetch(`${this.baseUrl}/users/${userId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
},
});
if (!response.ok) {
throw new Error(`Failed to delete user: ${response.statusText}`);
}
return response.json();
}
}
React Hook Example
import { useState, useEffect } from 'react';
export const useUsers = (filters: any = {}) => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [pagination, setPagination] = useState(null);
const fetchUsers = async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams();
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
if (Array.isArray(value)) {
value.forEach(v => params.append(`${key}[]`, v));
} else {
params.append(key, String(value));
}
}
});
const response = await fetch(`/api/users?${params}`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('accessToken')}`,
},
});
if (!response.ok) {
throw new Error('Failed to fetch users');
}
const data = await response.json();
setUsers(data.users);
setPagination(data.pagination);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, [filters]);
return { users, loading, error, pagination, refetch: fetchUsers };
};
π Next Steps
Now that you understand the Users API, explore the Authentication API for authentication features, or check out our Flutter Integration Guide for mobile development.
Authentication API
Sign up, sign in, and token management
Flutter Integration
Complete Flutter implementation guide