How do I add a new API endpoint?
Objective: This article explains how to add a new API endpoint path and handler.
Steps:
- Add a new path definition and configuration in the relevant file:
modules/<module>/contracts/api/paths/...
- Configure security if applicable.
- Add any new schemas if applicable.
- Add any new parameters if applicable.
- Create a new handler with the same name as the
operationId
property in the path configured in step 1.modules/<module>/api/handlers/...
- 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: