> ## 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

# Create Employee

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.
</Note>

## Request

### Headers

<ParamField header="x-api-key" type="string" required>
  Your API key for authentication

  **Example:** `sk_live_1234567890abcdef`
</ParamField>

<ParamField header="x-organization-id" type="string" required>
  Your organization UUID

  **Example:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`
</ParamField>

### Body Parameters

<ParamField body="name" type="string">
  Employee's full name (1-255 characters)

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

  **Example:** `"John Smith"`
</ParamField>

<ParamField body="email" type="string">
  Employee's email address

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

  **Example:** `"john.smith@company.com"`
</ParamField>

<ParamField body="situation" type="string" required>
  Employment situation

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

  **Example:** `"active"`
</ParamField>

<ParamField body="status" type="string" required>
  Data collection status

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

  **Example:** `"uploaded"`
</ParamField>

## Response

<ResponseField name="id" type="string">
  Unique identifier (UUID) for the employee
</ResponseField>

<ResponseField name="name" type="string | null">
  Employee's full name
</ResponseField>

<ResponseField name="email" type="string | null">
  Employee's email address
</ResponseField>

<ResponseField name="organization_id" type="string">
  Organization UUID
</ResponseField>

<ResponseField name="situation" type="string | null">
  Employment status: `active`, `inactive`, or `terminated`
</ResponseField>

<ResponseField name="status" type="string">
  Data status: `uploaded` or `loading`
</ResponseField>

<ResponseField name="periods" type="array | null">
  List of commuting periods (empty for new employees)
</ResponseField>

<ResponseField name="created_at" type="datetime">
  Timestamp when the employee was created
</ResponseField>

<ResponseField name="updated_at" type="datetime | null">
  Timestamp when the employee was last updated
</ResponseField>

## Example

<CodeGroup>
  ```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));
  ```
</CodeGroup>

### 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:** Missing or invalid API key

```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 from [Settings -> API](https://app.dcycle.io/settings/api).

### 404 Not Found

**Cause:** Organization not found

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "code": "ORGANIZATION_NOT_FOUND",
  "detail": "Organization with id=UUID('...') not found"
}
```

**Solution:** Verify that the `x-organization-id` header contains a valid organization UUID.

### 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)}")
```

## Next Steps

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

<CardGroup cols={2}>
  <Card title="Create Commuting Period" icon="route" href="/api-reference/employees/commuting-periods/create">
    Add commuting data for the employee
  </Card>

  <Card title="List Employees" icon="list" href="/api-reference/employees/list">
    View all employees and their emissions
  </Card>

  <Card title="Employee Commuting Guide" icon="book" href="/guides/emissions/scope-3-category-7-employee-commuting">
    Learn about tracking commuting emissions
  </Card>

  <Card title="Update Employee" icon="pencil" href="/api-reference/employees/update">
    Modify employee details
  </Card>
</CardGroup>
