Custom Directus Endpoints: Extending REST API for Any Business Logic

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

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.

Showing 1 of 1All 2062 services
Custom Directus Endpoints: Extending REST API for Any Business Logic
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Custom Directus Endpoints: Extending REST API for Any Business Logic

Many projects on Directus face tasks that cannot be solved with the built-in API. A typical example: placing an order in an e-commerce store. You need to check stock, create a record in the orders table, generate a Stripe payment session, and send an email to the customer. Using standard methods, this turns into a chain of webhooks and external services, complicating maintenance. A custom endpoint solves the problem with a single POST request. We develop such extensions for e-commerce, SaaS, and corporate portals. Our experience: over 15 projects, average development time 3 days. You get an API that perfectly matches your business processes without unnecessary layers.

Endpoint Extension is a mechanism that allows you to add new routes to your Directus API via a familiar Express router. You get full control over logic and response structure, access to Directus services (ItemsService, etc.) and the database schema, the ability to integrate with any external API (payment systems, CRM), and flexible access management at the endpoint level. Each endpoint undergoes code review and is covered by tests. Experience with Directus: over 4 years, more than 10 projects implemented.

What Problems We Solve

Problem 1: Transactional business logic. When creating an order, you need to atomically deduct stock, create an order record, and initiate payment. A custom endpoint implements the transaction using Directus services and a payment gateway. Errors are rolled back, data remains consistent.

Problem 2: Aggregated reports. The standard API cannot calculate sales totals by status over a period. We write a single endpoint that performs filtering and aggregation on the server, returning a ready JSON for the dashboard. Report generation time drops from several hours to a few seconds.

Problem 3: Webhooks from external systems. Stripe, PayPal, and other services send webhooks that need to be processed and update data in Directus. A custom endpoint is the ideal place for receiving and verifying webhooks. We guarantee processing with 99.9% uptime.

Example: Checkout on Directus

Consider a typical e-commerce scenario. We need a POST /checkout endpoint that accepts cart, shipping address, and payment method. On the server:

  1. Verify user authentication
  2. Use ItemsService to get data for each product (price, stock)
  3. If stock is insufficient, return a 409 error
  4. Create an order record with the total amount
  5. Create a Stripe payment session and return the payment link
  6. After successful payment, Stripe sends a webhook that updates the order status
// extensions/endpoints/checkout/index.ts
import type { EndpointExtensionContext } from '@directus/types'
import { Router } from 'express'

export default (router: Router, { services, getSchema, env, logger }: EndpointExtensionContext) => {

  // POST /checkout — place an order
  router.post('/checkout', async (req, res) => {
    const schema = await getSchema()
    const { ItemsService } = services

    // Check authentication
    if (!req.accountability?.user) {
      return res.status(401).json({ errors: [{ message: 'Unauthorized' }] })
    }

    const { items, shipping_address, payment_method } = req.body

    if (!items?.length) {
      return res.status(400).json({ errors: [{ message: 'Cart is empty' }] })
    }

    try {
      const productsService = new ItemsService('products', { schema, accountability: req.accountability })

      // Check stock and calculate total
      let total = 0
      const enrichedItems: any[] = []

      for (const item of items) {
        const product = await productsService.readOne(item.product_id, {
          fields: ['id', 'name', 'price', 'stock'],
        })

        if (product.stock < item.quantity) {
          return res.status(409).json({
            errors: [{ message: `Insufficient stock for "${product.name}"` }],
          })
        }

        total += product.price * item.quantity
        enrichedItems.push({ ...item, price: product.price, name: product.name })
      }

      // Create order
      const ordersService = new ItemsService('orders', { schema, accountability: req.accountability })
      const order = await ordersService.createOne({
        user: req.accountability.user,
        items: enrichedItems,
        total,
        shipping_address,
        status: 'pending',
        date_created: new Date().toISOString(),
      })

      // Create payment session
      const paymentSession = await createPaymentSession(order, total, env)

      return res.json({
        data: {
          orderId: order,
          paymentUrl: paymentSession.url,
          total,
        },
      })
    } catch (error) {
      logger.error('Checkout error:', error)
      return res.status(500).json({ errors: [{ message: 'Checkout failed' }] })
    }
  })

  // POST /checkout/webhook/stripe
  router.post('/webhook/stripe', async (req, res) => {
    const sig = req.headers['stripe-signature'] as string

    let event
    try {
      event = verifyStripeWebhook(req.rawBody, sig, env.STRIPE_WEBHOOK_SECRET)
    } catch {
      return res.status(400).json({ error: 'Webhook signature invalid' })
    }

    if (event.type === 'checkout.session.completed') {
      const session = event.data.object
      const orderId = session.metadata?.orderId

      if (orderId) {
        const schema = await getSchema()
        const ordersService = new services.ItemsService('orders', { schema })

        await ordersService.updateOne(Number(orderId), {
          status: 'paid',
          payment_id: session.payment_intent,
          paid_at: new Date().toISOString(),
        })
      }
    }

    return res.json({ received: true })
  })

  // GET /reports/sales
  router.get('/reports/sales', async (req, res) => {
    // Admin only
    if (!req.accountability?.admin) {
      return res.status(403).json({ errors: [{ message: 'Admin access required' }] })
    }

    const { period = 'week' } = req.query
    const schema = await getSchema()
    const ordersService = new services.ItemsService('orders', { schema, accountability: req.accountability })

    const periodDays: Record<string, number> = { day: 1, week: 7, month: 30 }
    const days = periodDays[period as string] || 7
    const since = new Date(Date.now() - days * 86400000).toISOString()

    const orders = await ordersService.readByQuery({
      filter: {
        date_created: { _gte: since },
        status: { _in: ['paid', 'shipped', 'delivered'] },
      },
      fields: ['id', 'total', 'date_created', 'status'],
      limit: -1,
    })

    const totalRevenue = orders.reduce((sum: number, o: any) => sum + (o.total || 0), 0)

    return res.json({
      data: {
        count: orders.length,
        revenue: totalRevenue,
        avgOrder: orders.length > 0 ? Math.round(totalRevenue / orders.length) : 0,
        period,
      },
    })
  })

  // GET /search
  router.get('/search', async (req, res) => {
    const { q, collections = 'articles,products' } = req.query as { q: string; collections: string }

    if (!q || q.length < 2) {
      return res.json({ data: [] })
    }

    const schema = await getSchema()
    const collectionList = (collections as string).split(',')

    const searchMap: Record<string, string[]> = {
      articles: ['title', 'excerpt'],
      products: ['name', 'description'],
      pages: ['title'],
    }

    const results = await Promise.all(
      collectionList
        .filter(c => searchMap[c])
        .map(async collection => {
          const service = new services.ItemsService(collection, { schema, accountability: req.accountability })
          const orFilter = searchMap[collection].map(field => ({
            [field]: { _icontains: q },
          }))

          const items = await service.readByQuery({
            filter: { _or: orFilter },
            fields: ['id', ...searchMap[collection]],
            limit: 5,
          })

          return items.map((item: any) => ({ ...item, _collection: collection }))
        })
    )

    return res.json({ data: results.flat() })
  })
}

async function createPaymentSession(orderId: number, total: number, env: any) {
  // Stripe checkout session
  const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${env.STRIPE_SECRET_KEY}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      'payment_method_types[]': 'card',
      'line_items[0][price_data][currency]': 'rub',
      'line_items[0][price_data][unit_amount]': String(Math.round(total * 100)),
      'line_items[0][price_data][product_data][name]': `Order #${orderId}`,
      'line_items[0][quantity]': '1',
      mode: 'payment',
      'metadata[orderId]': String(orderId),
      success_url: `${env.FRONTEND_URL}/order/${orderId}/success`,
      cancel_url: `${env.FRONTEND_URL}/cart`,
    }),
  })
  return response.json()
}
Solution Architecture

Client sends request -> Directus checks authentication -> custom endpoint processes logic via ItemsService and external API. All requests are logged, errors handled centrally. This approach eliminates the need for a separate microservice.

How Custom Endpoints Speed Up Development?

A custom Directus endpoint is 3–5 times faster to develop compared to writing a separate microservice. Ready-made plugins do not offer such flexibility. In one project, we implemented 10+ endpoints in 2 weeks, whereas a microservice would have taken a month. This approach reduces integration budget by 2–3 times and pays for itself within 2–3 months due to reduced development time.

What to Choose: Custom Endpoint vs Standard API?

Scenario Custom Endpoint Standard API
Simple record creation Overkill
Complex validation with external call Only via custom
Aggregated report ❌ (only with hooks)
Payment gateway integration
Multi-collection search

What’s Included

  • Source code of the extension in TypeScript with comments
  • package.json configuration for Directus Extension
  • Deployment instructions (copy to extensions folder, restart)
  • Postman collection with example requests
  • Error handling and input validation
  • 30 days of support after delivery

Process

  1. Requirements analysis — you describe needed endpoints, we clarify details
  2. Design — agree on route structure and response format
  3. Implementation — write code in TypeScript, connect Directus services
  4. Testing — cover critical cases with unit tests, test in a production-like environment
  5. Deployment — deliver the build and documentation

Estimated Timelines

Number of Endpoints Timeline
1–2 simple (validation, integration) 1–2 days
3–4 with external APIs (payments, reports) 3–5 days
5+ complex with webhooks 5–7 days

Exact timelines are calculated after a brief. Contact us — we’ll assess your project for free.

Why Choose Us

Over 4 years of experience with Directus: we have developed for e-commerce, CMS, and SaaS. Warranty on all extensions — we fix bugs free for one month. Transparent code — all changes in Git, mandatory code review. Post-launch support — we consult and refine as needed.

Order custom Directus endpoints turnkey. Get an API that perfectly matches your business processes. For a free evaluation of your project, contact us — we will prepare a proposal within 1 business day.

API Development with REST, GraphQL, WebSocket, and tRPC

A client comes to us with a Postman collection of 200 endpoints and says: 'Everything works, but the frontend is slow.' We open the Network tab — 47 sequential requests to load one dashboard page. Each one waits for the previous. This is not a server speed issue — it's an API architecture problem. With 10 years on the market, we've redesigned dozens of such integrations, and we guarantee: the right protocol and contract solve the problem at its root.

When REST stops being enough

REST works well for simple CRUD operations. But as soon as a mobile app appears alongside the web interface, over-fetching begins: the mobile app requests /api/users/123 and gets a 4KB object, but only needs name and avatar. Multiply that by a list of 50 users — 200KB traffic instead of 8KB.

GraphQL solves this with selection sets. The client describes exactly the fields it needs, and the server returns only those. On a project with React Native + Next.js, we migrated from REST to Apollo Server: payload size on the main screen dropped from 340KB to 28KB — a 92% traffic savings. Our certified engineers confirm: the typical pain when adopting GraphQL is N+1 query. A resolver for the author field on a post calls SELECT * FROM users WHERE id = ? for each post in the list. On a page with 20 posts — 21 database queries. Solved with DataLoader — it batches queries and turns them into one SELECT * FROM users WHERE id IN (...).

What is tRPC and how is it better than REST/GraphQL?

If the entire stack is TypeScript (Next.js + Node/Bun), tRPC removes a whole layer of problems. You define a procedure on the server — the client gets full type-safety automatically, without code generation and without Swagger. Renamed a field in the Zod schema — TypeScript highlights all places on the frontend where it's used. tRPC reduces code by 2 times compared to REST + Swagger + openapi-typescript: no need to maintain a separate specification and generate types — everything is inferred from runtime validators. However, tRPC is not suitable if the API is consumed by third-party clients or mobile apps in other languages — in such cases we use GraphQL or REST with OpenAPI specification.

WebSocket and real-time: when SSE, when WS?

HTTP polling every 5 seconds is an illusion of real-time with up to 5 seconds delay and useless server load. For chats, live notifications, collaborative editing — WebSocket or Server-Sent Events. SSE is a one-way stream from server to client, works over ordinary HTTP, automatically reconnects. Suitable for notifications, data streaming, progress bars. WebSocket is bidirectional, needed for chats and collaborative features. Experience shows: 80% of 'real-time' tasks are solved with SSE, not WebSocket — fewer infrastructure complexities.

A typical mistake: opening a WebSocket connection for each page component. On one project, the dashboard opened 12 parallel WS connections. The correct approach is one connection manager at the application level, subscriptions through it. In our work results, we always transfer the connection scheme and a ready solution.

Protocol Typing Over-fetching Versioning Real-time
REST Weak (OpenAPI) Yes URL / Header Polling
GraphQL Strong (SDL) No Deprecation Subscriptions
tRPC Full (TypeScript) No TypeScript checks Subscriptions (optional)

Swagger / OpenAPI as a contract

Documentation written after the fact becomes outdated the day after release. We write the OpenAPI 3.1 specification before development starts; it becomes the contract between frontend and backend. The frontend generates types via openapi-typescript, the backend validates incoming data using generated schemas. Contract deviation from implementation is caught on CI, not during review. For Laravel — l5-swagger or dedoc/scramble. For Node.js — @fastify/swagger or Zod + zod-to-openapi.

How to properly authenticate an API?

JWT with long-lived access tokens without rotation is a source of problems when compromised. The correct scheme: access token for 15 minutes, refresh token for 30 days with rotation on each use. Refresh token stored in an httpOnly cookie, access token in memory (not in localStorage). For inter-service communication — API Keys with scope limitations or mTLS. OAuth 2.0 with PKCE for public clients (SPA, mobile).

How to handle versioning and backward compatibility?

Breaking changes in an API without versioning break clients. Three approaches we use in projects:

Method Example When to use
URL versioning /api/v2/ REST API with long-term legacy support
Header versioning Accept: application/vnd.api+json;version=2 Minimal URL changes
Evolutionary (deprecation) Adding fields, GraphQL deprecated directive For GraphQL — smooth field removal

We guarantee backward compatibility through automated checks (oasdiff) on CI.

How we develop APIs: step-by-step plan

  1. Analysis — audit of current integrations, data schema compilation, protocol selection (REST/GraphQL/tRPC/WebSocket).
  2. Contract design — OpenAPI or SDL (GraphQL) before the first line of code.
  3. Development — implementation per contract, unit tests for each endpoint.
  4. Load testing — k6: 500 virtual users, 10 minutes, p95 latency ≤ 200ms.
  5. Deployment — CI/CD with backward compatibility check, automatic documentation publication.
  6. Team training — handover of Postman collection or Playground, connection instructions.
Typical mistakes we eliminate
  • N+1 on queries without DataLoader.
  • No rate limiting — DDOS through unauthenticated endpoints.
  • Storing access token in localStorage.
  • Opening multiple WebSocket connections instead of a single connection manager.
  • Documentation not updated after release.

What is included (deliverables)

  • OpenAPI 3.1 specification (or SDL for GraphQL).
  • Generated client types for TypeScript / Dart / Kotlin.
  • Set of automated tests covering all endpoints (unit + integration).
  • Load tests (k6) and report (p50/p95/p99 latency, RPS).
  • Documentation in Swagger UI / Redoc / GraphiQL.
  • Team training (2–4 hour workshop).
  • Support for 30 days after delivery (per contract).

Our experience

  • 10+ years in the API development market.
  • 200+ completed projects (REST, GraphQL, WebSocket, tRPC).
  • 50+ certified engineers (AWS, Kubernetes, API Design).
  • Traffic savings averaging 85% when migrating from REST to GraphQL for mobile apps.
  • 100% backward compatibility — not a single broken client in the last 3 years.

Timeline

API development for a typical SaaS project with 30–50 endpoints: from 3 to 8 weeks depending on business logic complexity and number of external integrations. Migration of an existing REST API to GraphQL: from 2 to 6 weeks. Adding a WebSocket layer to an existing backend: from 1 to 3 weeks. Cost is calculated individually after an audit. Get a consultation — contact us to discuss your project.