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:
- Verify user authentication
- Use ItemsService to get data for each product (price, stock)
- If stock is insufficient, return a 409 error
- Create an order record with the total amount
- Create a Stripe payment session and return the payment link
- 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
- Requirements analysis — you describe needed endpoints, we clarify details
- Design — agree on route structure and response format
- Implementation — write code in TypeScript, connect Directus services
- Testing — cover critical cases with unit tests, test in a production-like environment
- 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.







