REST API
Relevant source files
The following files were used as context for generating this wiki page:
- packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
- packages/twenty-server/src/engine/core-modules/open-api/open-api.service.ts
- packages/twenty-front/src/pages/settings/developers/playground/SettingsRestPlayground.tsx
- packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts
- packages/twenty-server/test/integration/rest/suites/page-layout.integration-spec.ts
- packages/twenty-apps/community/webmetic/README.md
- packages/twenty-server/test/integration/rest/suites/rest-api-core-create-one.integration-spec.ts
The Twenty REST API provides a comprehensive, versioned interface for developers to interact with both CRM data and its underlying metadata. It is built on NestJS and follows standard RESTful principles, using HTTP verbs to perform CRUD (Create, Read, Update, Delete) operations on various resources. The API is designed to be flexible and powerful, offering advanced features for filtering, pagination, and ordering.
To facilitate development and exploration, the API is self-documenting via an OpenAPI specification, which can be accessed through dedicated endpoints. This specification powers an interactive API Playground within the Twenty application, allowing developers to test endpoints directly. The API is split into two main schemas: core for data manipulation (e.g., companies, people) and metadata for schema manipulation (e.g., custom objects, page layouts).
Architecture
The REST API is handled by the RestApiCoreController on the backend. This controller acts as a generic router, capturing all requests to /rest/* and delegating them to the RestApiCoreService for processing. This design allows for dynamic handling of requests for any data object without needing a separate controller for each entity.
All endpoints are protected by a series of guards to ensure security and proper authorization:
JwtAuthGuard: Validates the JSON Web Token.WorkspaceAuthGuard: Ensures the user has access to the specified workspace.CustomPermissionGuard: Checks if the user has the required permissions for the requested action.
Sources: packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts:18-20
Request Handling Flow
The following diagram illustrates how an incoming REST API request is processed by the server.
This diagram shows the flow of a request from the client through authentication and authorization guards to the controller, which then passes it to the service layer for business logic execution.
Sources: packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
Authentication
All REST API requests must be authenticated using a Bearer Token. The token should be included in the Authorization header of each request. These tokens are workspace-scoped and can be generated in the Settings → Playground section of the Twenty application.
Example cURL request:
curl -H 'Authorization: Bearer <token>' <server>/rest/core/companies
The OpenAPI specification defines this security scheme, ensuring that interactive documentation tools like the API Playground prompt for the token.
// packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:70-77
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
description:
'Enter the token with the `Bearer: ` prefix, e.g. "Bearer abcde12345".',
},
},
Sources: packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:11-21, 70-83
Endpoints and Operations
The RestApiCoreController uses wildcard paths to handle requests for different objects dynamically. The HTTP verb determines the action to be performed.
| HTTP Method & Path | Controller Handler | Service Method | Description |
|---|---|---|---|
POST /batch/*path | handleApiPostBatch | createMany | Creates multiple records in a single request. |
POST *path/duplicates | handleApiFindDuplicates | findDuplicates | Finds duplicate records based on provided criteria. |
POST *path | handleApiPost | createOne | Creates a single new record. |
GET *path/groupBy | handleApiGroupBy | groupBy | Groups records by a specified field. |
GET *path | handleApiGet | get | Retrieves a single record (by ID) or a list of records. |
DELETE *path | handleApiDelete | delete | Deletes one or more records. |
PATCH /restore/*path | handleApiRestore | restore | Restores one or more soft-deleted records. |
PATCH *path/merge | handleApiMerge | mergeMany | Merges multiple records into a single record. |
PATCH *path | handleApiPatch | update | Updates one or more records. |
PUT *path | handleApiPut | update | An alias for PATCH for backward compatibility. |
Sources: packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts:25-150
Integration tests demonstrate the usage of these endpoints for both data and metadata objects, such as creating, updating, and deleting pageLayouts and pageLayoutWidgets.
Sources: packages/twenty-server/test/integration/rest/suites/page-layout.integration-spec.ts, packages/twenty-server/test/integration/rest/suites/page-layout-widget.integration-spec.ts
Querying Features
The REST API provides powerful and flexible parameters for querying lists of records.
Filtering
The filter query parameter allows for precise data retrieval.
| Comparator | Description | Example |
|---|---|---|
eq | Equal to | filter=status[eq]:"open" |
neq | Not equal to | filter=status[neq]:"closed" |
in | Value is in the provided array | filter=id[in]:["id-1","id-2"] |
containsAny | Array field contains any of the values | filter=tags[containsAny]:["lead","hot"] |
is | Is NULL or NOT_NULL | filter=deletedAt[is]:NULL |
gt, gte | Greater than, Greater than or equal to | filter=createdAt[gte]:"2024-01-01" |
lt, lte | Less than, Less than or equal to | filter=amount[lt]:1000 |
startsWith | String starts with a value | filter=name[startsWith]:"Acme" |
like, ilike | SQL LIKE/ILIKE (case-insensitive) pattern matching | filter=owner.name[ilike]:"%smith%" |
- Multiple conditions are joined by
AND. - Advanced logical operators
or(...),and(...), andnot(...)are also supported.
Sources: packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:24-52
Pagination
All list endpoints use cursor-based pagination.
| Parameter | Description | Default | Max |
|---|---|---|---|
limit | The maximum number of records to return per page. | 60 | 60 |
starting_after | The endCursor from the previous page to fetch the next page. | - | - |
ending_before | The startCursor from the current page to fetch the previous page. | - | - |
The response for a paginated request includes a pageInfo object with hasNextPage, startCursor, and endCursor.
Sources: packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:54-68
Ordering
The order_by parameter controls the sorting of results.
- Format:
field1,field2[DIRECTION] - Directions:
AscNullsFirst,AscNullsLast,DescNullsFirst,DescNullsLast. - Example:
order_by=createdAt[DescNullsLast],id[AscNullsFirst]
Sources: packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:88-96
OpenAPI Specification & API Playground
Twenty automatically generates an OpenAPI v3.1.1 specification for its REST API. This is handled by the OpenApiService, which constructs the schema by combining a base definition with dynamically generated paths and schemas for all available data objects.
The API is divided into two schemas:
core: For core CRM data entities (Companies, People, Opportunities, etc.).metadata: For entities that define the structure of the CRM (Objects, Fields, Page Layouts, etc.).
These schemas are available at the following endpoints:
/rest/open-api/core/rest/open-api/metadata
Sources: packages/twenty-server/src/engine/core-modules/open-api/open-api.service.ts, packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:7-9
API Playground
The frontend includes an API Playground, which is an interactive UI for exploring and testing the REST API. It is built using swagger-ui-react.
The following diagram shows how the API Playground is initialized.
This sequence shows the frontend playground fetching the OpenAPI schema from the backend to render the interactive API documentation.
Sources: packages/twenty-front/src/pages/settings/developers/playground/SettingsRestPlayground.tsx:30-38
Integration Example
Community applications leverage the REST API to extend Twenty's functionality. For example, the "Webmetic Visitor Intelligence" app uses several REST endpoints to sync data between Webmetic and Twenty.
The app performs the following actions:
GET /rest/metadata/objects: To check the data model.GET /rest/companies: To find existing companies.POST /rest/companies: To create new companies.PATCH /rest/companies/:id: To update existing companies.POST /rest/websiteLeads: To create new custom object records.
This demonstrates how the generic REST API can be used to interact with both standard and custom objects.
Sources: packages/twenty-apps/community/webmetic/README.md
An integration test for creating a person record shows how to set the createdBy field, which defaults to FieldActorSource.API but can be overridden. If an authenticated user makes the request, the source is automatically set to MANUAL and linked to the workspaceMemberId.