> ## Documentation Index
> Fetch the complete documentation index at: https://code.dcycle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Employee

> Add a new employee to your organization for commuting tracking

[← Employees API](https://code.dcycle.io/api-reference/employees/overview.md)

> [!WARNING]
>
> **Deprecated.** Use [`POST /v2/employees`](https://code.dcycle.io/api-reference/employees/create-v2): up to 1,000 employees per request, all
> or nothing, idempotent. To reuse an existing employee (`reuse_existing`) or assign a survey template
> (`survey_template_id`), use this endpoint: `POST /v2/employees` does neither. This endpoint keeps working; its responses carry `Deprecation` and `Link: </v2/employees>;
>     rel="successor-version"` headers. Its responses also carry `Sunset: Fri, 30 Apr 2027 00:00:00 GMT`: the endpoint is
> retired on **April 30, 2027** (see the [changelog](https://code.dcycle.io/api-reference/changelog.md)).

Create a new employee record in your organization. After creating an employee, you can add commuting periods to track their transportation emissions.

> [!NOTE]
>
> **Name or Email Required**: At least one of `name` or `email` must be provided when creating an employee.

## Request

### Headers

**x-api-key** `string` *required*

Your API key for authentication

**Example:** `sk_live_1234567890abcdef`

**x-organization-id** `string` *required*

Your organization UUID

**Example:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`

### Query Parameters

**reuse\_existing** `boolean` (default: false)

Return the organization's enabled employee with this email (case-insensitive) instead of a `409`, so a response can be added to someone who already exists.

### Body Parameters

**name** `string`

Employee's full name (1-255 characters)

**Required if `email` is not provided**

**Example:** `"John Smith"`

**email** `string`

Employee's email address

**Required if `name` is not provided**

**Example:** `"john.smith@company.com"`

**situation** `string` *required*

Employment situation

**Available values:** `active`, `inactive`, `terminated`

**Example:** `"active"`

**status** `string` *required*

Data collection status

**Available values:** `uploaded`, `loading`

**Example:** `"uploaded"`

## Response

**id** `string`

Unique identifier (UUID) for the employee

**name** `string | null`

Employee's full name

**email** `string | null`

Employee's email address

**organization\_id** `string`

Organization UUID

**situation** `string | null`

Employment status: `active`, `inactive`, or `terminated`

**status** `string`

Data status: `uploaded` or `loading`

**periods** `array | null`

List of commuting periods (empty for new employees)

**created\_at** `datetime`

Timestamp when the employee was created

**updated\_at** `datetime | null`

Timestamp when the employee was last updated

## Example

```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST "https://api.dcycle.io/v1/employees" \
  -H "x-api-key: ${DCYCLE_API_KEY}" \
  -H "x-organization-id: ${DCYCLE_ORG_ID}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Smith",
    "email": "john.smith@company.com",
    "situation": "active",
    "status": "uploaded"
  }'
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
import os

api_key = os.getenv("DCYCLE_API_KEY")
org_id = os.getenv("DCYCLE_ORG_ID")

headers = {
    "x-api-key": api_key,
    "x-organization-id": org_id,
    "Content-Type": "application/json"
}

payload = {
    "name": "John Smith",
    "email": "john.smith@company.com",
    "situation": "active",
    "status": "uploaded"
}

response = requests.post(
    "https://api.dcycle.io/v1/employees",
    headers=headers,
    json=payload
)

employee = response.json()
print(f"Employee created: {employee['id']}")
print(f"Name: {employee['name']}")
```

```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const axios = require('axios');

const apiKey = process.env.DCYCLE_API_KEY;
const orgId = process.env.DCYCLE_ORG_ID;

const headers = {
  'x-api-key': apiKey,
  'x-organization-id': orgId,
  'Content-Type': 'application/json'
};

const payload = {
  name: "John Smith",
  email: "john.smith@company.com",
  situation: "active",
  status: "uploaded"
};

axios.post(
  'https://api.dcycle.io/v1/employees',
  payload,
  { headers }
)
.then(response => {
  const employee = response.data;
  console.log(`Employee created: ${employee.id}`);
  console.log(`Name: ${employee.name}`);
})
.catch(error => console.error(error));
```

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "John Smith",
  "email": "john.smith@company.com",
  "organization_id": "a8315ef3-dd50-43f8-b7ce-d839e68d51fa",
  "situation": "active",
  "status": "uploaded",
  "periods": null,
  "created_at": "2024-11-24T10:30:00Z",
  "updated_at": "2024-11-24T10:30:00Z"
}
```

## Common Errors

### 401 Unauthorized

**Cause:** The key is invalid or revoked (`INVALID_API_KEY`), expired (`API_KEY_EXPIRED`), belongs neither to the
organization in `x-organization-id` nor to one of its parents (`API_KEY_ORG_MISMATCH`, whether or not that organization
exists), or has no owner (`API_KEY_NO_OWNER`). A request carrying no credentials at all answers
`AUTHENTICATION_REQUIRED`. See [Errors](https://code.dcycle.io/api-reference/errors.md#codes).

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid API key",
  "code": "INVALID_API_KEY"
}
```

**Solution:** Verify your API key is valid and active. Get a new one in **Company settings → API Keys**.
For `API_KEY_ORG_MISMATCH`, send the id of the key's organization or of one of its subsidiaries.

### 422 Validation Error

**Cause:** Missing required parameters or invalid values

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["body"],
      "msg": "Either name or email must be provided",
      "type": "value_error"
    }
  ]
}
```

**Solution:** Ensure at least `name` or `email` is provided, and `situation` and `status` have valid enum values.

## Use Cases

### Create Employee with Full Details

Add an employee with all available information:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def create_employee(name, email, situation="active"):
    """Create a new employee with full details"""
    payload = {
        "name": name,
        "email": email,
        "situation": situation,
        "status": "uploaded"
    }

    response = requests.post(
        "https://api.dcycle.io/v1/employees",
        headers=headers,
        json=payload
    )

    return response.json()

# Create employee
employee = create_employee(
    name="John Smith",
    email="john@company.com"
)
print(f"Created: {employee['id']}")
```

### Create Employee for Survey

Create an employee with just email for survey distribution:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def create_employee_for_survey(email):
    """Create employee for survey - email only"""
    payload = {
        "email": email,
        "situation": "active",
        "status": "loading"  # Will be updated after survey
    }

    response = requests.post(
        "https://api.dcycle.io/v1/employees",
        headers=headers,
        json=payload
    )

    return response.json()

# Create employees for survey
emails = ["alice@company.com", "bob@company.com", "carol@company.com"]
for email in emails:
    employee = create_employee_for_survey(email)
    print(f"Created {email}: {employee['id']}")
```

### Create Employee and Add Commuting Period

Complete workflow to track an employee's commuting:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def create_employee_with_commuting(name, email, commuting_data):
    """Create employee and add their commuting period"""

    # Step 1: Create employee
    employee = requests.post(
        "https://api.dcycle.io/v1/employees",
        headers=headers,
        json={
            "name": name,
            "email": email,
            "situation": "active",
            "status": "uploaded"
        }
    ).json()

    # Step 2: Add commuting period
    period_data = {
        "employee_id": employee["id"],
        "commuting_type": "in_itinere",
        "situation": "active",
        "response_medium": "manual",
        **commuting_data
    }

    period = requests.post(
        "https://api.dcycle.io/v1/employee-historic",
        headers=headers,
        json=period_data
    ).json()

    return employee, period

# Create employee with car commute
employee, period = create_employee_with_commuting(
    name="John Smith",
    email="john@company.com",
    commuting_data={
        "start_date": "2024-01-01",
        "end_date": "2024-12-31",
        "transport_type": "car",
        "vehicle_size": "medium",
        "fuel_type": "petrol",
        "total_km": 15,
        "weekly_travels": [0, 1, 2, 3, 4],
        "daily_trips": 1,
        "carpool": False,
        "renewable_energy": None
    }
)

print(f"Employee: {employee['name']}")
print(f"Annual CO2e: {period['co2e']} kg")
```

### Bulk Create Employees

Add multiple employees from a list:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def bulk_create_employees(employees_data):
    """Create multiple employees at once"""
    created = []
    failed = []

    for emp_data in employees_data:
        try:
            response = requests.post(
                "https://api.dcycle.io/v1/employees",
                headers=headers,
                json={
                    "name": emp_data.get("name"),
                    "email": emp_data.get("email"),
                    "situation": "active",
                    "status": "uploaded"
                }
            )

            if response.status_code == 201:
                created.append(response.json())
            else:
                failed.append({"data": emp_data, "error": response.text})

        except Exception as e:
            failed.append({"data": emp_data, "error": str(e)})

    return created, failed

# Bulk create
employees_to_create = [
    {"name": "Alice Johnson", "email": "alice@company.com"},
    {"name": "Bob Williams", "email": "bob@company.com"},
    {"name": "Carol Davis", "email": "carol@company.com"},
]

created, failed = bulk_create_employees(employees_to_create)
print(f"Created: {len(created)}, Failed: {len(failed)}")
```

> [!NOTE]
>
> After creating an employee, you'll typically want to:
>
> 1. **Add Commuting Period**: Create a commuting period to track their transportation
> 2. **Send Survey**: Use the survey feature to collect commuting data from the employee
> 3. **View Emissions**: Retrieve the employee to see calculated CO2e

> [card] [Create Commuting Period](https://code.dcycle.io/api-reference/employees/commuting-periods/create.md)
>
> Add commuting data for the employee

> [card] [List Employees](https://code.dcycle.io/api-reference/employees/list.md)
>
> View all employees and their emissions

> [card] [Employee Commuting Guide](https://code.dcycle.io/guides/emissions/scope-3-category-7-employee-commuting.md)
>
> Learn about tracking commuting emissions

> [card] [Update Employee](https://code.dcycle.io/api-reference/employees/update.md)
>
> Modify employee details


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.