Users API
👤 User Management
The Users API provides self-service user account management capabilities including registration, profile updates, and account deletion. Users can manage their own accounts and profile information through these endpoints.
Base URL
All user endpoints are prefixed with:
Authentication
Most user endpoints require authentication (except registration). Include the Bearer token in the Authorization header:
Data Models
UserRegister
Request model for user registration.
UserUpdate
Request model for updating user profile information.
Note: Regular users cannot modify is_superuser
field - this is admin-only.
UserResponse
Standard user response format.
{
"id": 123,
"email": "user@example.com",
"full_name": "John Doe",
"is_active": true,
"is_superuser": false,
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-15T10:30:00Z"
}
Endpoints
Register User
Create a new user account (public endpoint - no authentication required).
Request Body
Response
Status Code: 201 Created
{
"id": 124,
"email": "newuser@example.com",
"full_name": "New User",
"is_active": true,
"is_superuser": false,
"created_at": "2025-01-15T11:00:00Z",
"updated_at": "2025-01-15T11:00:00Z"
}
Security Notes
is_superuser
is automatically set tofalse
for securityis_active
is set totrue
by default (users are immediately active)- Passwords are securely hashed before storage
Error Responses
400 Bad Request - Validation error
422 Unprocessable Entity - Invalid request data
{
"detail": [
{
"loc": ["body", "email"],
"msg": "field required",
"type": "value_error.missing"
}
]
}
Get Current User
Retrieve information about the currently authenticated user.
Response
Status Code: 200 OK
{
"id": 123,
"email": "user@example.com",
"full_name": "John Doe",
"is_active": true,
"is_superuser": false,
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-15T10:30:00Z"
}
Error Responses
401 Unauthorized - Invalid or missing authentication
Update User Profile
Update the current user's profile information.
Request Body
Optional Fields:
- email
: New email address (must be unique)
- full_name
: Updated display name
- is_active
: User status (users can deactivate their own accounts)
Restricted Fields:
- is_superuser
: Cannot be modified by regular users
- password
: Use password change endpoint (not implemented in this API)
Response
Status Code: 200 OK
{
"id": 123,
"email": "updated.email@example.com",
"full_name": "Updated Full Name",
"is_active": true,
"is_superuser": false,
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-15T14:00:00Z"
}
Error Responses
400 Bad Request - Validation error
404 Not Found - User not found (shouldn't happen for authenticated users)
Delete User Account
Permanently delete the current user's account.
Response
Status Code: 200 OK
Important Notes
- Permanent Action: Account deletion cannot be undone
- Data Cleanup: All user data (including chat history, API keys, memories) will be deleted
- Authentication: User's JWT tokens will become invalid immediately
- Related Data: All associated records (sessions, preferences, etc.) are removed
Error Responses
404 Not Found - User not found
500 Internal Server Error - Deletion failed
Integration Examples
Python Example
import requests
from typing import Dict, Any, Optional
class QuantbotUsersClient:
def __init__(self, base_url: str, access_token: Optional[str] = None):
self.base_url = base_url
self.headers = {}
if access_token:
self.headers["Authorization"] = f"Bearer {access_token}"
self.headers["Content-Type"] = "application/json"
def register(self, email: str, password: str, full_name: str) -> Dict[str, Any]:
"""Register a new user account"""
response = requests.post(
f"{self.base_url}/api/v1/users/register",
headers={"Content-Type": "application/json"}, # No auth needed
json={
"email": email,
"password": password,
"full_name": full_name
}
)
response.raise_for_status()
return response.json()
def get_current_user(self) -> Dict[str, Any]:
"""Get current user information"""
response = requests.get(
f"{self.base_url}/api/v1/users/me",
headers=self.headers
)
response.raise_for_status()
return response.json()
def update_profile(self, email: Optional[str] = None,
full_name: Optional[str] = None,
is_active: Optional[bool] = None) -> Dict[str, Any]:
"""Update user profile"""
update_data = {}
if email is not None:
update_data["email"] = email
if full_name is not None:
update_data["full_name"] = full_name
if is_active is not None:
update_data["is_active"] = is_active
response = requests.put(
f"{self.base_url}/api/v1/users/me",
headers=self.headers,
json=update_data
)
response.raise_for_status()
return response.json()
def delete_account(self) -> Dict[str, Any]:
"""Delete current user account"""
response = requests.delete(
f"{self.base_url}/api/v1/users/me",
headers=self.headers
)
response.raise_for_status()
return response.json()
# Usage examples
# 1. Registration (no auth needed)
users_client = QuantbotUsersClient("http://localhost:8000")
new_user = users_client.register(
email="developer@company.com",
password="secure_dev_password",
full_name="Developer Account"
)
print(f"✅ Registered user: {new_user['email']} (ID: {new_user['id']})")
# 2. Authenticated operations (need to login first and get token)
# After authentication...
authenticated_client = QuantbotUsersClient(
"http://localhost:8000",
"your_access_token_here"
)
# Get current user info
user_info = authenticated_client.get_current_user()
print(f"👤 Current user: {user_info['full_name']} ({user_info['email']})")
# Update profile
updated_user = authenticated_client.update_profile(
full_name="Updated Developer Name",
email="new.developer@company.com"
)
print(f"✏️ Profile updated: {updated_user['full_name']}")
# Account management
print(f"📊 Account Status: {'Active' if updated_user['is_active'] else 'Inactive'}")
print(f"🔑 Admin Rights: {'Yes' if updated_user['is_superuser'] else 'No'}")
TypeScript Example
interface UserRegistration {
email: string;
password: string;
full_name: string;
}
interface UserUpdate {
email?: string;
full_name?: string;
is_active?: boolean;
}
interface User {
id: number;
email: string;
full_name: string;
is_active: boolean;
is_superuser: boolean;
created_at: string;
updated_at: string;
}
class QuantbotUsersAPI {
constructor(private baseURL: string, private accessToken?: string) {}
private get headers() {
const headers: Record<string, string> = {
'Content-Type': 'application/json'
};
if (this.accessToken) {
headers['Authorization'] = `Bearer ${this.accessToken}`;
}
return headers;
}
async register(userData: UserRegistration): Promise<User> {
const response = await fetch(`${this.baseURL}/api/v1/users/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' }, // No auth for registration
body: JSON.stringify(userData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Registration failed: ${error.detail}`);
}
return await response.json();
}
async getCurrentUser(): Promise<User> {
const response = await fetch(`${this.baseURL}/api/v1/users/me`, {
method: 'GET',
headers: this.headers
});
if (!response.ok) {
throw new Error(`Failed to get user info: ${response.statusText}`);
}
return await response.json();
}
async updateProfile(updates: UserUpdate): Promise<User> {
const response = await fetch(`${this.baseURL}/api/v1/users/me`, {
method: 'PUT',
headers: this.headers,
body: JSON.stringify(updates)
});
if (!response.ok) {
const error = await response.json();
throw new Error(`Profile update failed: ${error.detail}`);
}
return await response.json();
}
async deleteAccount(): Promise<{message: string}> {
const response = await fetch(`${this.baseURL}/api/v1/users/me`, {
method: 'DELETE',
headers: this.headers
});
if (!response.ok) {
throw new Error(`Account deletion failed: ${response.statusText}`);
}
return await response.json();
}
setAccessToken(token: string): void {
this.accessToken = token;
}
}
// Usage examples
const usersAPI = new QuantbotUsersAPI('http://localhost:8000');
// Registration flow
async function registerUser() {
try {
const newUser = await usersAPI.register({
email: 'investor@example.com',
password: 'secure_investment_password',
full_name: 'Professional Investor'
});
console.log('✅ Registration successful:', newUser.email);
console.log('🆔 User ID:', newUser.id);
return newUser;
} catch (error) {
console.error('❌ Registration failed:', error);
throw error;
}
}
// Authenticated user management
async function manageUserProfile(accessToken: string) {
usersAPI.setAccessToken(accessToken);
try {
// Get current user info
const currentUser = await usersAPI.getCurrentUser();
console.log('👤 Current user:', currentUser.full_name);
// Update profile
const updatedUser = await usersAPI.updateProfile({
full_name: 'Senior Professional Investor',
email: 'senior.investor@example.com'
});
console.log('✏️ Profile updated:', updatedUser.full_name);
console.log('📧 New email:', updatedUser.email);
// Check account status
if (!updatedUser.is_active) {
console.log('⚠️ Account is inactive');
}
return updatedUser;
} catch (error) {
console.error('❌ Profile management failed:', error);
throw error;
}
}
// Account deletion with confirmation
async function deleteUserAccount(accessToken: string, confirmEmail: string) {
usersAPI.setAccessToken(accessToken);
try {
// Verify user before deletion
const currentUser = await usersAPI.getCurrentUser();
if (currentUser.email !== confirmEmail) {
throw new Error('Email confirmation does not match');
}
// Perform deletion
const result = await usersAPI.deleteAccount();
console.log('🗑️ Account deleted:', result.message);
return result;
} catch (error) {
console.error('❌ Account deletion failed:', error);
throw error;
}
}
User Account Lifecycle
Registration Flow
- Public Registration: No authentication required
- Email Validation: System validates email format and uniqueness
- Password Security: Passwords are hashed using secure algorithms
- Default Settings: New users are active by default, not superusers
- Immediate Access: Users can login immediately after registration
Profile Management
- Self-Service: Users can only modify their own profiles
- Email Changes: System validates new email addresses for uniqueness
- Name Updates: Full name can be changed at any time
- Account Status: Users can deactivate their own accounts
Account Deletion
- Confirmation Required: Permanent action requiring authentication
- Data Cleanup: All related data is removed (sessions, API keys, memories)
- Immediate Effect: JWT tokens become invalid immediately
- No Recovery: Deleted accounts cannot be restored
Security Considerations
Data Protection
- Password Security: All passwords are securely hashed (never stored in plain text)
- Email Validation: Email addresses are validated and must be unique
- Self-Service Only: Users can only access and modify their own data
Access Control
- Authentication Required: All endpoints except registration require valid JWT
- No Cross-User Access: Users cannot view or modify other users' data
- Admin Restrictions: Regular users cannot grant themselves admin privileges
Account Security
- Token Invalidation: Account deletion immediately invalidates all tokens
- Audit Logging: All user operations are logged for security monitoring
- Rate Limiting: Registration endpoint includes rate limiting to prevent abuse
Error Handling
Common Error Responses
400 Bad Request - Validation error
401 Unauthorized - Authentication required or invalid
404 Not Found - User not found
422 Unprocessable Entity - Invalid request format
{
"detail": [
{
"loc": ["body", "email"],
"msg": "field required",
"type": "value_error.missing"
}
]
}
500 Internal Server Error - Server error
Related APIs
- Authentication API - Login and token management
- Admin API - Administrative user management (superuser only)
- API Keys API - User-specific API key management
- Memory API - User data cleanup on account deletion