Skip to main content

How do I add a new API endpoint?

Objective: This article explains how to add a new API endpoint path and handler.

Steps:

  1. Add a new path definition and configuration in the relevant file:
    • modules/<module>/contracts/api/paths/...
  2. Configure security if applicable.
  3. Add any new schemas if applicable.
  4. Add any new parameters if applicable.
  5. Create a new handler with the same name as the operationId property in the path configured in step 1.
    • modules/<module>/api/handlers/...
  6. Build and test.

Example:

// Path configuration
// modules/<module>/contracts/api/paths/...

...

'/path/to/endpoint': {
get: {
operationId: 'exampleHandler', // <-- This must match the name of the handler function.
summary: 'My API endpoint',
description: 'Does something amazing',
tags: ['<relevant tag>'],
security: [
// Configure security if applicable.
...
],
parameters: [
// Configure security if applicable.
...
],
responses: schema.common.responses.all()
}
}
// API handler
// modules/<module>/api/handlers/...

import type { ApiHandler } from '@hectare/platform.components.context'
import { Response } from '@hectare/platform.components.common'

// Note: The name of the function must match the name of the operationId

export const exampleHandler: ApiHandler = async (context): Promise<Response> => {
return context.event.response.ok('Hello world!')
}

Related Articles: