DBMS Topics
Create User
title: "Users API - Create User",
import { HttpMethodBadge } from '../components/HttpMethodBadge' import { EndpointUrl } from '../components/EndpointUrl' import { ParameterTable } from '../components/ParameterTable' import { CodeExample } from '../components/CodeExample' import { ResponseExample } from '../components/ResponseExample' import { AuthBadge } from '../components/AuthBadge' import { RateLimitInfo } from '../components/RateLimitInfo' import { ErrorCodesTable } from '../components/ErrorCodesTable' import { TryItOut } from '../components/TryItOut' import { Callout } from '../components/Callout' import { TabGroup, Tab } from '../components/Tabs' import { StatusBadge } from '../components/StatusBadge' import { SchemaViewer } from '../components/SchemaViewer' import { SecurityBadge } from '../components/SecurityBadge'
<HttpMethodBadge method="POST" /> <EndpointUrl url="/v2/users" />
<div className="api-meta"> <AuthBadge type="[REDACTED_TOKEN]" scopes={["users:write", "users:admin"]} /> <RateLimitInfo requests={100} window="1 minute" tier="standard" /> <StatusBadge status="stable" since="v2.0.0" /> </div>
Creates a new user in your organization. They'll get a verification email unless you set skipVerification to true (needs admin scope).
Request
Headers
<ParameterTable parameters={[ { name: "Authorization", type: "string", required: true, description: "[REDACTED_TOKEN] or API key for authentication" }, { name: "Content-Type", type: "string", required: true, description: "Must be application/json" }, { name: "X-Request-Id", type: "string", required: false, description: "Unique request identifier for idempotency. If provided, duplicate requests with the same ID within 24 hours will return the original response." }, { name: "X-Organization-Id", type: "string", required: false, description: "Override the default organization. Only available for multi-org API keys." }, ]} />
Body Parameters
<ParameterTable parameters={[ { name: "email", type: "string", required: true, description: "User's email address. Must be unique within the organization. Maximum 254 characters.", example: "jane.doe@example.com" }, { name: "firstName", type: "string", required: true, description: "User's first name. 1-100 characters, Unicode supported.", example: "Jane" }, { name: "lastName", type: "string", required: true, description: "User's last name. 1-100 characters, Unicode supported.", example: "Doe" }, { name: "password", type: "string", required: false, description: "Initial password. Must be 8-128 characters with at least one uppercase, one lowercase, one number, and one special character. If omitted, user will be prompted to set one via email.", example: "S3cure!Pass#2024" }, { name: "role", type: "enum", required: false, description: "User's role within the organization. Determines permissions and access levels.", enum: ["viewer", "editor", "admin", "owner"], default: "viewer" }, { name: "department", type: "string", required: false, description: "Department or team the user belongs to. Used for organizational filtering.", example: "Engineering" }, { name: "avatar", type: "string (URL)", required: false, description: "URL to the user's avatar image. Must be HTTPS and a valid image format (jpg, png, webp). Maximum 5MB.", example: "https://cdn.example.com/avatars/jane.jpg" }, { name: "preferences", type: "object", required: false, description: "User preference settings for notifications, locale, and display options.", children: [ { name: "locale", type: "string", description: "ISO 639-1 language code", default: "en" }, { name: "timezone", type: "string", description: "IANA timezone string", default: "UTC" }, { name: "notifications", type: "object", description: "Notification channel preferences" }, ] }, { name: "metadata", type: "object", required: false, description: "Custom key-value pairs for storing additional data. Maximum 50 keys, 500 characters per value.", example: { employeeId: "EMP-12345", costCenter: "CC-789" } }, { name: "skipVerification", type: "boolean", required: false, description: "Skip email verification step. Requires users:admin scope. User will be immediately active.", default: "false" }, { name: "sendWelcomeEmail", type: "boolean", required: false, description: "Whether to send a welcome email to the new user with onboarding instructions.", default: "true" }, { name: "tags", type: "string[]", required: false, description: "Array of tags for categorization. Maximum 20 tags, 50 characters each.", example: ["engineering", "frontend", "team-alpha"] }, ]} />
Request Body Example
Response
Success Response
<StatusBadge status="201 Created" variant="success" />
Code Examples
``bash title="cURL" curl -X POST https://api.acmecloud.io/v2/users \ -H "Authorization: [REDACTED_TOKEN]" \ -H "Content-Type: application/json" \ -H "X-Request-Id: req_unique_12345" \ -d '{ "email": "jane.doe@example.com", "firstName": "Jane", "lastName": "Doe", "role": "editor", "department": "Engineering", "preferences": { "locale": "en-US", "timezone": "America/New_York" }, "tags": ["engineering", "frontend"] }' ` `javascript title="Node.js / Fetch" const createUser = async (userData) => { const response = await fetch('https://api.acmecloud.io/v2/users', { method: 'POST', headers: { 'Authorization': Bearer ${process.env.ACME_API_KEY}`, 'Content-Type': 'application/json', 'X-Request-Id': crypto.randomUUID(), }, body: JSON.stringify({ email: userData.email, firstName: userData.firstName, lastName: userData.lastName, role: userData.role || 'viewer', department: userData.department, preferences: { locale: 'en-US', timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, notifications: { email: true, push: true, sms: false, digest: 'daily', }, }, tags: userData.tags || [], sendWelcomeEmail: true, }), });
if (!response.ok) { const error = await response.json(); throw new Error(API Error ${response.status}: ${error.error.message}); }
const result = await response.json(); return result.data; };
// Usage try { const user = await createUser({ email: 'jane.doe@example.com', firstName: 'Jane', lastName: 'Doe', role: 'editor', department: 'Engineering', tags: ['engineering', 'frontend'], }); console.log(User created: ${user.id}); } catch (error) { console.error('Failed to create user:', error.message); } `` ``python title="Python (requests)" import requests import os import uuid
class AcmeClient: def __init__(self, api_key: str = None): self.api_key = api_key or os.environ.get("ACME_API_KEY") self.base_url = "https://api.acmecloud.io/v2" self.session = requests.Session() self.session.headers.update({ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", })
def create_user( self, email: str, first_name: str, last_name: str, role: str = "viewer", department: str = None, preferences: dict = None, metadata: dict = None, tags: list = None, skip_verification: bool = False, ) -> dict: """Create a new user in the organization.""" payload = { "email": email, "firstName": first_name, "lastName": last_name, "role": role, "sendWelcomeEmail": True, "skipVerification": skip_verification, }
if department: payload["department"] = department if preferences: payload["preferences"] = preferences if metadata: payload["metadata"] = metadata if tags: payload["tags"] = tags
response = self.session.post( f"{self.base_url}/users", json=payload, headers={"X-Request-Id": str(uuid.uuid4())}, )
if response.status_code == 201: return response.json()["data"] else: error = response.json() raise Exception( f"API Error {response.status_code}: " f"{error['error']['message']}" )
# Usage client = AcmeClient()
try: user = client.create_user( email="jane.doe@example.com", first_name="Jane", last_name="Doe", role="editor", department="Engineering", preferences={ "locale": "en-US", "timezone": "America/New_York", "notifications": {"email": True, "push": True}, }, tags=["engineering", "frontend"], ) print(f"User created: {user['id']}") except Exception as e: print(f"Failed to create user: {e}") `` ``go title="Go" package main
import ( "bytes" "encoding/json" "fmt" "net/http" "os"
"github.com/google/uuid" )
type CreateUserRequest struct { Email string json:"email" FirstName string json:"firstName" LastName string json:"lastName" Role string json:"role,omitempty" Department string json:"department,omitempty" Preferences *UserPreferences json:"preferences,omitempty" Tags []string json:"tags,omitempty" Metadata map[string]string json:"metadata,omitempty" }
type UserPreferences struct { Locale string json:"locale" Timezone string json:"timezone" }
func CreateUser(req CreateUserRequest) (map[string]interface{}, error) { body, err := json.Marshal(req) if err != nil { return nil, fmt.Errorf("marshal error: %w", err) }
httpReq, err := http.NewRequest( "POST", "https://api.acmecloud.io/v2/users", bytes.NewBuffer(body), ) if err != nil { return nil, fmt.Errorf("request error: %w", err) }
httpReq.Header.Set("Authorization", "Bearer "+os.Getenv("ACME_API_KEY")) httpReq.Header.Set("Content-Type", "application/json") httpReq.Header.Set("X-Request-Id", uuid.New().String())
client := &http.Client{} resp, err := client.Do(httpReq) if err != nil { return nil, fmt.Errorf("request failed: %w", err) } defer resp.Body.Close()
var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result)
if resp.StatusCode != 201 { return nil, fmt.Errorf("API error %d: %v", resp.StatusCode, result["error"]) }
return result["data"].(map[string]interface{}), nil }
| { name | "Free", requests: 20, window: "1 minute", burst: 5 }, |
| { name | "Standard", requests: 100, window: "1 minute", burst: 20 }, |
| { name | "Pro", requests: 500, window: "1 minute", burst: 50 }, |
| { name | "Enterprise", requests: 5000, window: "1 minute", burst: 500 }, |
X-RateLimit-Limit: 100 X-RateLimit-Remaining: 97 X-RateLimit-Reset: 1710500460 X-RateLimit-RetryAfter: 0
| status | 400, |
| code | "VALIDATION_ERROR", |
| message | "Request body validation failed", |
| description | "One or more fields contain invalid data. Check the `details` array for specific field errors.", |
| status | 401, |
| code | "UNAUTHORIZED", |
| message | "Invalid or expired authentication token", |
| description | "The provided API key or [REDACTED_TOKEN] is invalid, expired, or missing.", |
| status | 403, |
| code | "FORBIDDEN", |
| message | "Insufficient permissions", |
| description | "Your token lacks the required scope. Make sure you have `users:write` or `users:admin`.", |
| status | 409, |
| code | "CONFLICT", |
| message | "User with this email already exists", |
| description | "A user with the provided email address already exists in this organization.", |
| status | 422, |
| code | "UNPROCESSABLE_ENTITY", |
| message | "Password does not meet requirements", |
| description | "The password doesn't meet complexity requirements (8+ chars, mixed case, number, special char).", |
| status | 429, |
| code | "RATE_LIMITED", |
| message | "Too many requests", |
| description | "You've exceeded the rate limit for your plan tier. Wait and retry with exponential backoff.", |
| status | 500, |
| code | "INTERNAL_ERROR", |
| message | "An unexpected error occurred", |
| description | "Something went wrong on our end. If this persists, contact support with the requestId.", |
{ "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Request body validation failed", "details": [ { "field": "email", "message": "Invalid email format", "code": "invalid_format" }, { "field": "role", "message": "Must be one of: viewer, editor, admin, owner", "code": "invalid_enum" } ], "requestId": "req_abc123def456", "documentation": "https://docs.acmecloud.io/errors/VALIDATION_ERROR" } }
| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/v2/users` | List all users with pagination and filtering |
| `GET` | `/v2/users/:id` | Get a specific user by ID |
| `PATCH` | `/v2/users/:id` | Update user profile and settings |
| `DELETE` | `/v2/users/:id` | Deactivate or permanently delete a user |
| `POST` | `/v2/users/:id/verify` | Manually verify a user's email |
| `POST` | `/v2/users/:id/reset-password` | Trigger password reset flow |
| `GET` | `/v2/users/:id/activity` | Get user activity log |
{ "event": "user.created", "timestamp": "2024-03-15T10:30:00.000Z", "data": { "userId": "usr_a1b2c3d4e5f6", "email": "jane.doe@example.com", "role": "editor", "organizationId": "org_x9y8z7w6" }, "meta": { "webhookId": "wh_123456", "deliveryId": "dlv_abcdef" } }
| Configure webhooks in your [Dashboard Settings](https | //dashboard.acmecloud.io/settings/webhooks). |
| apiVersion | "v2", |
| lastTested | "2024-03-10", |
| sdkSupport | ["javascript", "python", "go", "ruby", "php"], |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Create User.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this MDX topic.
Search Terms
mdx, mdx tutorial, learn mdx, markdown, jsx, tutorial, examples, api
Related MDX Topics