Skip to content

Create a department

Use this REST API v2 operation to add a department. A key with the departments:write scope is required, and the write is attributed either to the key owner or to the user identified by X-On-Behalf-Of. The API holds the request while the department is being created, then answers 201 with the new department together with its parent and approvers. Should creation outlast the wait window, the answer is 202 Accepted and includes an operation you can poll for the outcome.

Endpoint and authorization

The call is a POST to /v2/departments, with the API key presented in the Authorization header as a Bearer token. That key needs the departments:write scope. By default the key owner is treated as the acting user; to attribute the write to someone else, include X-On-Behalf-Of with that person's user ID. Using this header depends on two conditions: the key must hold the users:act-on-behalf scope, and the key owner must have management responsibility for the target user. If either condition is missing, the API answers with 403 ON_BEHALF_OF_NOT_ALLOWED. GET requests disregard the header entirely.

Request body fields

The body is JSON. The table below maps each field to its requirement, default and purpose so you can build a valid payload before sending it.

Field map

Use this map to check required fields and defaults before you send the request.

Approvers and approval levels

At least one entry in approvers is required, and each userId may appear only once. Each approver's levels defaults to ["FIRST"]. A SECOND level needs a plan with multi-level approval; without it, the request fails with 403 FEATURE_NOT_IN_PLAN. The response includes each approver's userId and levels. A background process writes approvers, so they may briefly lag right after a write.

Sub-departments and defaults

A department is top-level when parentId is left out. To place it under an existing department instead, pass that department's ID as parentId. The userIds array is optional: any users listed there are transferred into the newly created department, and leaving the array out is equivalent to sending an empty one. isDefault is likewise optional and begins as false; setting it to true designates the new department as the company's default. Any property not defined by the schema, or any value whose type does not match, causes validation to fail.

Retry safety with Idempotency-Key

An Idempotency-Key header turns a create call into something you can safely attempt more than once. Accepted values run from 1 to 255 printable ASCII characters, and each key is remembered for 24 hours in the context of the API key that sent it. Repeating an identical request with the same key inside that period does not create a second department; instead the stored response is returned again, marked with the Idempotent-Replayed header. Problems are reported separately: pairing a key with a different request yields 422 IDEMPOTENCY_KEY_REUSED, sending a retry before the first attempt has finished yields 409 IDEMPOTENCY_REQUEST_IN_PROGRESS, and a key that does not meet the format rules yields 400 INVALID_IDEMPOTENCY_KEY.

Responses

A successful synchronous creation returns 201 with the department's id, name, isDefault flag, createdAt timestamp, optional parentId and approvers array. If the write is still running, or succeeded but its result could not be read back yet, the response is 202 Accepted with an operation object. The Location header carries the same URL as operation.url. Poll that URL until the status is SUCCEEDED or FAILED. A status of UNKNOWN means no result arrived within 15 minutes; the change may or may not have been applied, so read the resource to check. A result that arrives later still changes the status to SUCCEEDED or FAILED.

Error responses

Errors use a consistent envelope with error.code, error.name, error.description, error.resolution, error.requestId and optional error.details. The documented codes for this endpoint are 400 VALIDATION_ERROR with details.fields, 400 INVALID_REQUEST_BODY, 403 ON_BEHALF_OF_NOT_ALLOWED, 403 FORBIDDEN, 403 FEATURE_NOT_IN_PLAN when a SECOND approval level is requested without multi-level approval, 409 DUPLICATE_NAME when another department already uses the name, 422 UNKNOWN_USER_IDS when userIds or approvers name users who are not active users of the company, 422 PLAN_LIMIT_REACHED, and the Idempotency-Key codes. Include the requestId when contacting support.

Decision checklist before you send

  1. Confirm the key has departments:write and, if you use X-On-Behalf-Of, users:act-on-behalf. 2. Decide whether the department is top-level or a sub-department, and set parentId only for the latter. 3. Confirm at least one approver and check whether any approver needs SECOND level; if so, confirm the plan includes multi-level approval. 4. Decide whether to move users in with userIds and whether this should be the default department. 5. Generate an Idempotency-Key if you may retry the request. 6. After sending, branch on 201 versus 202: for 202, poll operation.url until SUCCEEDED or FAILED.

Example: a top-level department with one approver

The supplied example creates a top-level department named Dev Team with one approver and one user moved into the department. The request body is shown in the protected code module code0001. A successful 201 response returns the department object shown in code0002, including its id, name, isDefault, createdAt, parentId and approvers. If the response is 202, the operation object in code0003 shows the shape to poll.

Request field map
FieldRequiredDefaultPurpose
nameYes—Department name; length 1 or more
approversYes—At least one approver; each userId may appear only once
userIdsNo[]IDs of users to move into this department
parentIdNo—Parent department ID; omit for a top-level department
isDefaultNofalseWhether this becomes the company's default department
watchersToNotifyNo—Email addresses notified about leave requests in this department
keepLeaveRequestsOpenNo—Whether leave requests stay open instead of auto-expiring

Field requirements and defaults are taken from the supplied contract schema and request-body documentation. No runtime tests were performed.

Frequently asked questions

Which scope is required to create a department?

The API key must have the departments:write scope. If you use X-On-Behalf-Of, the key also needs users:act-on-behalf, and the key owner must manage the target user.

Can I create a department with more than one approval level?

Yes, but a SECOND approval level requires a plan with multi-level approval. Without it, the request fails with 403 FEATURE_NOT_IN_PLAN. Each approver's levels defaults to ["FIRST"].

What should I do if the response is 202 Accepted?

Poll the operation URL returned in operation.url until the status is SUCCEEDED or FAILED. If the status is UNKNOWN, no result arrived within 15 minutes; read the resource to check whether the change was applied.

Why did I get a 409 error?

A 409 DUPLICATE_NAME means another department already uses the name. A 409 IDEMPOTENCY_REQUEST_IN_PROGRESS means the first request with that Idempotency-Key is still running.

Why did I get a 422 UNKNOWN_USER_IDS error?

The userIds or approvers arrays name users who are not active users of the company. Check that every user ID belongs to an active user.

curl -X POST "$API_BASE_URL/v2/departments" \
  -H "Authorization: Bearer " \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Dev Team",
    "approvers": [
      {
        "userId": "user-63b17e97-d38b-4586-8498-bb4f5d2e2c14"
      }
    ],
    "userIds": [
      "user-cfe5d39b-f1f0-45aa-85cd-ce93e637a262"
    ]
  }'
{
  "data": {
    "id": "team-0a21c25e-6925-4a5b-90ee-ecf82096c4f6",
    "name": "Dev Team",
    "isDefault": false,
    "createdAt": "2022-08-22T15:00:00.000Z",
    "parentId": "team-969f8429-7dc3-48a1-96b1-6049a99dda06",
    "approvers": [
      {
        "userId": "user-63b17e97-d38b-4586-8498-bb4f5d2e2c14",
        "levels": [
          "FIRST"
        ]
      },
      {
        "userId": "user-0f3a9c1e-6c2b-4a5d-9e7f-1b2c3d4e5f60",
        "levels": [
          "SECOND"
        ]
      }
    ]
  }
}
{
  "operation": {
    "id": "pa_3f1c2b9e-8a47-4d5e-9c61-2b7f0e4a1d93",
    "status": "PENDING",
    "url": "/v2/operations/pa_3f1c2b9e-8a47-4d5e-9c61-2b7f0e4a1d93"
  }
}
{
  "error": {
    "code": "VALIDATION_ERROR",
    "name": "ValidationError",
    "description": "Example post details.",
    "resolution": "Fix the fields listed in details.fields and send the request again.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "details": {
      "fields": [
        {
          "path": "startDate",
          "message": "\"startDate\" is required"
        }
      ]
    }
  }
}
{
  "error": {
    "code": "UNAUTHORIZED",
    "name": "Unauthorized",
    "description": "Example post details.",
    "resolution": "Send a valid API key in the Authorization header as Bearer followed by the full vt_live_ key.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef"
  }
}
{
  "error": {
    "code": "INSUFFICIENT_SCOPE",
    "name": "InsufficientScope",
    "description": "Example post details.",
    "resolution": "Add the scopes listed in details.requiredScopes to the key in the OnlyLeave dashboard.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "details": {
      "requiredScopes": [
        "leaves:write"
      ]
    }
  }
}
{
  "error": {
    "code": "CONFLICT",
    "name": "Conflict",
    "description": "Example post details.",
    "resolution": "Read the resource again and retry with up-to-date values.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef"
  }
}
{
  "error": {
    "code": "LEAVE_NEGATIVE_BALANCE",
    "name": "LeaveNegativeBalance",
    "description": "Example post details.",
    "resolution": "Shorten the leave, use a different leave type, or ask an admin to adjust the quota.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef"
  }
}
{
  "error": {
    "code": "RATE_LIMITED",
    "name": "RateLimited",
    "description": "Example post details.",
    "resolution": "Wait a few seconds and retry, using the same Idempotency-Key for writes.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef"
  }
}
{
  "error": {
    "code": "INTERNAL_ERROR",
    "name": "InternalError",
    "description": "Example post details.",
    "resolution": "Retry later, and if it keeps happening, contact OnlyLeave support and quote the requestId.",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef"
  }
}

Idempotency-Key

FieldTypeRequiredDescriptionConstraints
Idempotency-KeystringNooptional key (1 to 255 printable ASCII characters) that makes a write request safe to retry. Keys are retained for 24 hours per API key. Retrying with the same key and the same request within those 24 hours replays the original response (with the Idempotent-Replayed header). Reusing the key with a different request returns 422 IDEMPOTENCY_KEY_REUSED ; retrying while the first request is still running returns 409 IDEMPOTENCY_REQUEST_IN_PROGRESS ; an invalid key returns 400 INVALID_IDEMPOTENCY_KEY .1 <= length <= 255

X-On-Behalf-Of

FieldTypeRequiredDescriptionConstraints
X-On-Behalf-OfstringNoID of the user the write is performed for. Requires the users:act-on-behalf scope, and the key owner must manage the target user; otherwise the request fails with 403 ON_BEHALF_OF_NOT_ALLOWED . Ignored on GET requests.

body

FieldTypeRequiredDescriptionConstraints
bodyobjectYes
body.namestringYesdepartment name1 <= length
body.approversarray<DepartmentApproverInput>Yesusers who approve leave requests for this department. At least one approver is required, and each userId may appear only once.1 <= items
body.approvers[]object
body.approvers[].userIdstringYesthe approver's user ID1 <= length
body.approvers[].levelsarray<string>Noapproval levels this user approves at. SECOND requires a plan with multi-level approval.["FIRST"]
1 <= items
body.approvers[].levels[]stringAllowed values: "FIRST" | "SECOND"
body.userIdsarray<string>NoIDs of the users to move into this department[]
body.userIds[]string1 <= length
body.parentIdstringNothe ID of the parent department, to make this a sub-department. Omit it for a top-level department.1 <= length
body.isDefaultbooleanNowhether this becomes the company's default departmentfalse
body.watchersToNotifyarray<string>Noemail addresses that are notified about leave requests in this department
body.watchersToNotify[]stringemail
body.keepLeaveRequestsOpenbooleanNowhether leave requests in this department stay open instead of auto-expiring

response

FieldTypeRequiredDescriptionConstraints
responseobject
response.dataobjectYesA department as returned by create and update, with its parent and approvers. The approvers are written by a background process, so they may briefly lag right after a write.
response.data.idstringYesdepartment ID
response.data.namestringYesdepartment name
response.data.isDefaultbooleanYeswhether this is the company's default department
response.data.createdAtstringYesa timestamp in the ISO 8601 formatFormat: date-time
response.data.parentIdstringNothe ID of the parent department, present only for a sub-department
response.data.approversarray<DepartmentApprover>Yesusers who approve leave requests for this department, and the levels they approve at
response.data.approvers[]object
response.data.approvers[].userIdstringYesthe approver's user ID
response.data.approvers[].levelsarray<string>Yesthe approval levels this user approves at; FIRST when none is stored
response.data.approvers[].levels[]stringAllowed values: "FIRST" | "SECOND"

response

FieldTypeRequiredDescriptionConstraints
responseobjectReturned with HTTP 202 when a write operation is still running, or succeeded but its result could not be read back yet. The Location header carries the same URL as operation.url . Poll it until the status is SUCCEEDED or FAILED .
response.operationobjectYes
response.operation.idstringYes
response.operation.statusstringYesoperation status. UNKNOWN means no result arrived within 15 minutes; the change may or may not have been applied, so read the resource to check. A result that arrives later still changes it to SUCCEEDED or FAILED.Allowed values: "PENDING" | "SUCCEEDED" | "FAILED" | "UNKNOWN"
response.operation.urlstringYes

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo

response

FieldTypeRequiredDescriptionConstraints
responseobjectError envelope returned by every endpoint, including authentication and rate limit errors. error.code is one of the codes in x-error-catalog .
response.errorobjectYes
response.error.codestringYesstable machine-readable error code
response.error.namestringYesshort human-readable error name
response.error.descriptionstringYeswhat went wrong
response.error.resolutionstringYeshow to fix the problem
response.error.requestIdstringYesrequest ID, include it when contacting support
response.error.detailsobjectNooptional additional information specific to the error code
response.error.details.[key: string]anyNo