NYYU Logo
APIUser

Get User by ID

Admin operation to retrieve any user's profile information by their unique ID

Get User by ID

ADMIN

Administrative operation to retrieve any user's complete profile information by their unique identifier. Requires admin privileges.

Query

GraphQL Schema

getUserById(userId: Int!): User

Parameters

userIdInt!
Required

The unique identifier of the user to retrieve. Must be a valid integer representing an existing user ID.

Return Type

Returns a complete User object for the specified user ID.

Example Usage

query {
  getUserById(userId: 12345) {
    id
    email
    name
    country
    role
    tierLevel
    regDate
    lastLoginDate
    verify {
      emailVerified
      phoneVerified
      kycVerified
      amlVerified
    }
    security {
      tfaEnabled
      authType
    }
  }
}
{
  "data": {
    "getUserById": {
      "id": 12345,
      "email": "user@example.com",
      "name": "John Doe",
      "country": "USA",
      "role": ["ROLE_USER"],
      "tierLevel": 2,
      "regDate": 1699564800000,
      "lastLoginDate": 1699651200000,
      "verify": {
        "emailVerified": true,
        "phoneVerified": true,
        "kycVerified": false,
        "amlVerified": false
      },
      "security": {
        "tfaEnabled": true,
        "authType": "password"
      }
    }
  }
}
import { GraphQLClient } from 'graphql-request';

const client = new GraphQLClient('https://api.nyyu.io/graphql', {
  headers: {
    authorization: `Bearer ${adminToken}`,
  },
});

const query = `
  query GetUserById($userId: Int!) {
    getUserById(userId: $userId) {
      id
      email
      name
      role
      tierLevel
      verify {
        emailVerified
        kycVerified
      }
    }
  }
`;

async function getUserById(userId: number) {
  try {
    const data = await client.request(query, { userId });
    console.log('User details:', data.getUserById);
    return data.getUserById;
  } catch (error) {
    console.error('Error fetching user:', error);
    throw error;
  }
}

// Usage
const user = await getUserById(12345);
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

transport = RequestsHTTPTransport(
    url='https://api.nyyu.io/graphql',
    headers={'authorization': f'Bearer {admin_token}'},
)

client = Client(transport=transport)

query = gql('''
  query GetUserById($userId: Int!) {
    getUserById(userId: $userId) {
      id
      email
      name
      role
      tierLevel
      verify {
        emailVerified
        kycVerified
      }
    }
  }
''')

def get_user_by_id(user_id: int):
    try:
        result = client.execute(query, variable_values={'userId': user_id})
        print(f"User details: {result['getUserById']}")
        return result['getUserById']
    except Exception as error:
        print(f"Error fetching user: {error}")
        raise

# Usage
user = get_user_by_id(12345)

Use Cases

User Investigation

Admin dashboard for investigating user accounts, reviewing verification status, and checking account details.

Support Tickets, Account Review

Moderation Tools

Access user information before performing moderation actions like suspension, role changes, or account restrictions.

User Moderation, Compliance

Analytics & Reporting

Retrieve detailed user information for analytics, reporting, and data analysis purposes.

Admin Analytics, User Reports

Customer Support

Support staff can look up user details to assist with customer inquiries and resolve issues effectively.

Help Desk, Support Dashboard

Security Considerations

Admin Access Only

This operation requires ROLE_ADMIN privileges. Unauthorized access attempts will be rejected with a 403 Forbidden error.

Audit Logging

All admin user lookups should be logged for security auditing. Track who accessed which user profiles and when.

Data Privacy Compliance

Ensure admin access to user data complies with GDPR, CCPA, and other data privacy regulations. Only access user data when necessary.

Sensitive Information

The returned User object contains sensitive personal information. Handle this data securely and never expose it to unauthorized parties.

Best Practices

Implementation Guidelines

1.
Validate User ID
Always validate that the user ID is a positive integer before making the query. Handle non-existent user IDs gracefully.
2.
Implement Audit Logs
Log every admin user lookup with timestamp, admin ID, and accessed user ID for compliance and security monitoring.
3.
Request Only Needed Fields
Select only the fields required for your use case. Minimize data transfer and reduce security exposure.
4.
Handle Deleted Users
Check the 'deleted' field to determine if a user account has been soft-deleted. Display appropriate messaging.

Error Handling

403 Forbidden

Requester does not have ROLE_ADMIN privileges

404 Not Found

No user exists with the specified ID

400 Bad Request

Invalid user ID format (must be a positive integer)

401 Unauthorized

Missing or invalid authentication token

async function getUserByIdWithErrorHandling(userId: number) {
  // Validate input
  if (!userId || userId <= 0) {
    throw new Error('Invalid user ID');
  }

  try {
    const data = await client.request(query, { userId });

    // Check if user is deleted
    if (data.getUserById.deleted === 1) {
      console.warn('User account has been deleted');
    }

    return data.getUserById;
  } catch (error) {
    if (error.response?.status === 403) {
      // Not authorized - redirect to admin login
      console.error('Admin privileges required');
      throw new Error('Insufficient permissions');
    } else if (error.response?.status === 404) {
      // User not found
      console.error(`User ${userId} not found`);
      throw new Error('User not found');
    } else if (error.response?.status === 400) {
      // Bad request
      console.error('Invalid request format');
      throw new Error('Invalid user ID format');
    } else {
      // Other errors
      console.error('Failed to fetch user:', error);
      throw error;
    }
  }
}

Administrative Workflow

Typical Admin Flow

1
Search for User
Use getUserById with the user's ID from a support ticket or search result
2
Review User Details
Check verification status, account age, tier level, and activity
3
Take Action
Based on findings, perform necessary actions (suspend, verify, update role, etc.)
4
Document Changes
Log all actions taken and reasons in the audit system