GraphQL API
Relevant source files
The following files were used as context for generating this wiki page:
- packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts
- packages/twenty-front/src/pages/settings/developers/playground/SettingsGraphQLPlayground.tsx
- packages/twenty-server/src/engine/api/graphql/workspace-resolver-builder/workspace-resolver.factory.ts
- packages/twenty-server/test/integration/graphql/codegen/index.ts
- packages/twenty-front/project.json
- packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-resolver.integration-spec.ts
- CLAUDE.md
The Twenty platform utilizes a GraphQL API as a primary interface for data communication between the twenty-server (backend) and twenty-front (frontend). Built with NestJS and GraphQL Yoga, it employs a code-first approach to schema generation. A key architectural feature is its ability to dynamically generate parts of the GraphQL schema and resolvers based on the workspace's custom data model, providing a flexible and extensible API tailored to each user's configuration.
The API is also exposed for developer use through an in-app GraphQL Playground, allowing for direct interaction and integration. Both REST and GraphQL APIs are available, with GraphQL being central to the core application's functionality.
Sources: CLAUDE.md, packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts
Architecture
The GraphQL API is a core component of the twenty-server package, built on NestJS. It handles requests from the frontend, processes them through dynamically generated resolvers, and interacts with the PostgreSQL database via TypeORM.
This diagram shows the high-level data flow for a GraphQL query.
Sources: CLAUDE.md
Key Components
| File/Component | Description | Package |
|---|---|---|
WorkspaceSchemaFactory | Dynamically generates GraphQL schema types (queries, mutations, objects) based on workspace metadata. | twenty-server |
WorkspaceResolverFactory | Dynamically creates GraphQL resolvers for the generated schema types. | twenty-server |
SettingsGraphQLPlayground.tsx | A React component that provides an interactive GraphiQL playground in the application settings. | twenty-front |
graphql:generate script | A command used by twenty-front to generate TypeScript types from the GraphQL schema for client-side type safety. | twenty-front |
| Integration Tests | A suite of tests that use introspection to validate the API and even auto-generate test files. | twenty-server |
Sources: packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts, packages/twenty-server/src/engine/api/graphql/workspace-resolver-builder/workspace-resolver.factory.ts, packages/twenty-front/src/pages/settings/developers/playground/SettingsGraphQLPlayground.tsx, packages/twenty-front/project.json
Dynamic Schema Generation
A standout feature of Twenty's GraphQL API is its ability to build the schema at runtime based on the user-defined data model (objects and fields). This process is primarily managed by WorkspaceSchemaFactory and WorkspaceResolverFactory.
The following diagram illustrates the schema generation flow:
Schema Factory (WorkspaceSchemaFactory)
This factory is responsible for creating GraphQL types. It iterates through the workspace's object metadata and generates corresponding GraphQLObjectType, GraphQLInputObjectType, and other necessary types. It dynamically constructs queries and mutations for each custom object, such as findMany, findOne, createOne, updateOne, and deleteOne.
Sources: packages/twenty-server/src/engine/api/graphql/workspace-schema.factory.ts:27-31
Resolver Factory (WorkspaceResolverFactory)
Complementing the schema factory, the WorkspaceResolverFactory builds the resolver functions that contain the business logic for the dynamically generated queries and mutations. It creates a generic resolver class for each object and attaches the appropriate methods to handle data operations.
Frontend Integration
The twenty-front application heavily relies on the GraphQL API for its data needs.
GraphQL Playground
Twenty provides a built-in GraphQL playground for developers, accessible in Settings → Developers → Playground. This feature uses the @graphiql/react library to provide an interactive IDE for exploring the schema and executing queries.
The playground is configured to fetch the schema from the /graphql endpoint and uses the current user's authentication token to make authorized requests.
// packages/twenty-front/src/pages/settings/developers/playground/SettingsGraphQLPlayground.tsx:34-44
const fetcher = createGraphiQLFetcher({
url: '/graphql',
headers: {
Authorization: `Bearer ${token}`,
},
});
return (
<div css={{ height: 'calc(100vh - 200px)' }}>
<GraphiQL fetcher={fetcher} />
</div>
);
Sources: packages/twenty-front/src/pages/settings/developers/playground/SettingsGraphQLPlayground.tsx:34-44
Code Generation
To ensure type safety, the frontend uses @graphql-codegen to generate TypeScript types from the API's schema. This is orchestrated by an nx command defined in packages/twenty-front/project.json.
// packages/twenty-front/project.json:134-148
"graphql:generate": {
"executor": "nx:run-commands",
"defaultConfiguration": "data",
"options": {
"cwd": "{projectRoot}",
"command": "dotenv graphql-codegen -- --config={args.config}"
},
"configurations": {
"data": {
"config": "codegen.cjs"
},
"metadata": {
"config": "codegen-metadata.cjs"
}
}
},
Running npx nx run twenty-front:graphql:generate triggers this process, which introspects the GraphQL endpoint and outputs typed hooks and utilities that can be used throughout the React application.
Sources: packages/twenty-front/project.json:134-148, CLAUDE.md
Authentication
All requests to the GraphQL API must be authenticated. This is done by including an Authorization header with a Bearer token (JWT).
Example of an authenticated request:
// packages/twenty-server/test/integration/graphql/codegen/index.ts:27-31
const fetchGraphQLSchema = async (): Promise<IntrospectionResponse> => {
const headers = {
Authorization: BEARER_TOKEN,
'Content-Type': 'application/json',
};
This token is generated upon user login and is scoped to a specific workspace. Tokens for testing and development can be generated in the GraphQL Playground settings.
Sources: packages/twenty-server/test/integration/graphql/codegen/index.ts:27-31, packages/twenty-server/src/engine/core-modules/open-api/utils/base-schema.utils.ts:13-15
Testing
The GraphQL API is extensively tested through integration tests. The project includes a sophisticated script that automates the creation of test files for resolvers.
Automated Test Generation
The script located at packages/twenty-server/test/integration/graphql/codegen/index.ts performs the following steps:
- Sends an introspection query to the running GraphQL endpoint.
- Parses the schema to identify all available queries.
- For each query that returns a connection (e.g., a list of objects) and has no required arguments, it generates a test file.
- The generated test file contains a basic integration test that calls the query and asserts that the response structure is correct.
- These files are written to the
test/integration/graphql/suites/object-generateddirectory.
This diagram illustrates the test generation workflow:
Resolver Integration Tests
Actual resolver tests, like page-layout-resolver.integration-spec.ts, use libraries such as graphql-tag and supertest to make direct API requests and assert the responses. These tests cover the full lifecycle of an entity: create, find, update, delete, and restore.
// packages/twenty-server/test/integration/graphql/suites/page-layout/page-layout-resolver.integration-spec.ts:200-209
it('should create a new page layout with all properties', async () => {
const input = {
name: 'Dashboard Page Layout',
type: PageLayoutType.DASHBOARD,
objectMetadataId: testObjectMetadataId,
};
const operation = createPageLayoutOperationFactory({ data: input });
const response = await makeGraphqlAPIRequest(operation);
assertGraphQLSuccessfulResponse(response);