REST and GraphQL API in Directus: Complex Queries and Optimization Cases

When building headless projects on Directus, standard API generation often falls short of covering business logic. A typical scenario: the frontend makes 30 requests for a catalog page due to N+1 relations, filters don't work for nested fields, and GraphQL throws errors on complex aggregations. The

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Frequently Asked Questions

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1281
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1237
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    977
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    1025
  • image_website-sbh_0.webp
    Website development for SBH Partners
    1103
  • image_website-_0.webp
    Website development for Red Pear
    550

When building headless projects on Directus, standard API generation often falls short of covering business logic. A typical scenario: the frontend makes 30 requests for a catalog page due to N+1 relations, filters don't work for nested fields, and GraphQL throws errors on complex aggregations. The client loses users due to slow load times. We are a team with five years of experience implementing Directus — we turn your API into a high-performance solution. Our clients save up to 40% on server resources and reduce TTFB from 2 seconds to 200 ms.

Problems We Solve

N+1 Queries with Relations

A standard REST request /items/articles returns only flat fields. If the frontend needs the author, category, and comments—it makes 3 additional requests per post. With 20 posts per page, that's 60 requests. The solution is to use fields=*,author.*,category.*,comments.* with a single request. But if you need to sort comments or limit their count, the deep parameter is required. We configure deep populate with custom sorting and limits, reducing requests to 1–2.

Filtering by Related Collections

A common task: show articles only from a specific category, but the category is a related record. In Directus, this is done via filter[category][slug][_eq]=tech. However, OR conditions with nested relations can produce incorrect results. For example, filter[_or][0][title][_icontains]=react&filter[_or][1][content][_icontains]=react works, but combining it with a filter on the author complicates the syntax. We use custom endpoints on Flows for complex logic.

Aggregations with Grouping

Dashboards often need monthly sales sums. Directus supports aggregate[sum]=total&groupBy[]=status, but you cannot group by two different fields in one request. We use the SDK and write custom SQL queries through migrations.

How We Do It: Stack and Use Case

A client project — an online store on Next.js + Directus 10. Task: build an API for a catalog with filters (price, brand, attributes), search via Meilisearch, and real-time cart updates. Stack: Directus (REST + WebSocket), Meilisearch for full-text search, Redis for caching.

Case: aggregating average check per day. Standard REST cannot do this—only one aggregation type per request. We wrote a custom endpoint on Flows with a SQL query:

SELECT DATE(date_created) as day, AVG(total) as avg_check FROM orders WHERE status = 'paid' GROUP BY day ORDER BY day; 

Result: 1 request instead of 30, dashboard speed increased 4x. The client saved $2000/month on caching and CDN.

Work Process

  1. Analysis: audit of current requests, identifying bottlenecks (Core Web Vitals, request count).
  2. Design: choose REST, GraphQL, or WebSocket for tasks. Define the relation and filter schema.
  3. Implementation: configure endpoints, custom Flows, optimization via fields and deep. For search, integrate Meilisearch or Elasticsearch.
  4. Testing: load testing (k6), check with 1000 concurrent requests.
  5. Deploy: set up rate limiting, CORS, SSL, caching (Redis/Varnish).

How to Set Up GraphQL in Directus?

Enable GraphQL by specifying in .env:

GRAPHQL_SDLFILE=/tmp/schema.graphql 

GraphQL is available at /graphql. In production, disable introspection via GRAPHQL_INTROSPECTION=false. Use mutations for creating records and subscriptions for realtime.

Why REST API Is Faster Than GraphQL?

In Directus, REST API uses database-level caching (query keys), while GraphQL does not. For simple selections, REST gives lower latency (20–30% faster). But GraphQL is more convenient for complex nested queries with different fields. The choice depends on the task: for public endpoints — REST, for admin panels — GraphQL.

How to Integrate Search via Meilisearch?

Meilisearch is connected as a service in Directus via a Hook or Flow. Configure indexing of fields, relevance, and filters. Example configuration:

{ "index": "articles", "primaryKey": "id", "searchableAttributes": ["title", "content"], "filterableAttributes": ["status", "category_id"] } 

After synchronization, data is available through a separate endpoint. Result: search in 10–50 ms instead of 500+ ms with full-text search in PostgreSQL.

Comparison of REST and GraphQL

Criterion REST GraphQL
Caching Built-in (URL as key) None (needs custom setup)
Overfetching Yes (if fields not specified) No (returns only requested fields)
Nested queries Via deep, complex for OR Natural (query language)
Performance Higher for simple selections Lower due to query parsing
Best for Public APIs, caching Complex client interfaces

Typical Mistakes When Setting Up Directus API

Mistake Consequence Solution
Incorrect deep syntax Error 500, empty response URL-encode parameters: deep[comments][_sort]=-date
Missing indexes Full scan, slow queries Create indexes on frequently filtered fields
Too broad fields High traffic, slow response Specify only necessary fields
Ignoring caching Excessive DB load Enable caching via Varnish/Cloudflare

What's Included

  • Audit of current requests and optimization.
  • Setup of REST, GraphQL, or WebSocket for tasks.
  • Writing custom endpoints on Flows for complex logic.
  • Search integration (Meilisearch/Elasticsearch).
  • Rate limiting, caching, security configuration.
  • API documentation (OpenAPI/Swagger).
  • Training for the client's team.
  • 1 month support after launch.

Timeline

Basic REST/GraphQL setup: 2 to 5 days. Custom endpoints and complex aggregations: 5 to 10 days. Exact timeline after audit.

Get a free consultation for your project. Order a Directus API audit — we'll propose an optimized solution.