Skip to main content

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": "[email protected]",
  "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:
FieldTypeRequiredDescription
firstNamestring❌User’s first name
lastNamestring❌User’s last name
agenumber❌Integer between 1-120
phoneNumberstring❌Valid phone number (must be unique)
avatarUrlstring❌URL to user’s avatar image
descriptionstring❌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": "[email protected]",
  "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:
ParameterTypeRequiredDescription
searchstring❌Search across firstName, lastName, email, phoneNumber
firstNamestring❌Filter by first name (partial match)
lastNamestring❌Filter by last name (partial match)
emailstring❌Filter by email (partial match)
phoneNumberstring❌Filter by phone number (partial match)
rolesstring[]❌Filter by roles (exact match)
isEmailVerifiedboolean❌Filter by email verification status
isActiveboolean❌Filter by account status
pagenumber❌Page number (default: 1)
limitnumber❌Items per page (default: 10, max: 100)
sortBystring❌Sort field (default: β€˜createdAt’)
sortOrderstring❌Sort order: β€˜asc’ or β€˜desc’ (default: β€˜desc’)
Success Response (200):
{
  "users": [
    {
      "id": "ck_123...",
      "email": "[email protected]",
      "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": "[email protected]",
  "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": "[email protected]",
    "phoneNumber": "+1234567891",
    "age": 29,
    "avatarUrl": "https://example.com/avatar.jpg",
    "description": "Updated description",
    "roles": ["admin"],
    "isEmailVerified": true,
    "isActive": true
  }'
Request Body:
FieldTypeRequiredDescription
firstNamestring❌User’s first name
lastNamestring❌User’s last name
emailstring❌Valid email address (must be unique)
phoneNumberstring❌Valid phone number (must be unique)
agenumber❌Integer between 1-120
avatarUrlstring❌URL to user’s avatar image
descriptionstring❌User’s bio/description
rolesstring[]❌User roles (admin only)
isEmailVerifiedboolean❌Email verification status (admin only)
isActiveboolean❌Account status (admin only)
Success Response (200):
{
  "id": "ck_123...",
  "email": "[email protected]",
  "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": "[email protected]",
    "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": "[email protected]",
    "password": "securePassword123",
    "phoneNumber": "+1234567891",
    "age": 30,
    "description": "New system administrator",
    "roles": ["admin"]
  }'
Request Body:
FieldTypeRequiredDescription
firstNamestringβœ…Admin’s first name
lastNamestringβœ…Admin’s last name
emailstringβœ…Valid email address (must be unique)
passwordstringβœ…Minimum 6 characters
phoneNumberstringβœ…Valid phone number (must be unique)
agenumberβœ…Integer between 1-120
descriptionstring❌Optional description
rolesstring[]❌User roles (default: [β€œadmin”])
Success Response (200):
{
  "message": "Admin created successfully",
  "admin": {
    "id": "ck_456...",
    "email": "[email protected]",
    "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 CodeDescriptionCommon Causes
400 Bad RequestInvalid request dataValidation errors, malformed JSON
401 UnauthorizedAuthentication requiredMissing/invalid token, expired token
403 ForbiddenInsufficient permissionsWrong role, not admin/super_admin
404 Not FoundResource not foundInvalid user ID, user doesn’t exist
409 ConflictResource conflictEmail/phone already exists
500 Internal Server ErrorServer errorDatabase issues, unexpected errors

Error Response Format

{
  "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.