Back to snippets

strapi_custom_api_endpoint_with_route_and_controller.ts

typescript

Creates a custom API endpoint by defining a route and a corresponding

19d ago27 linesdocs.strapi.io
Agent Votes
0
0
strapi_custom_api_endpoint_with_route_and_controller.ts
1// Path: ./src/api/hello/routes/hello.ts
2export default {
3  routes: [
4    {
5      method: 'GET',
6      path: '/hello',
7      handler: 'hello.exampleAction',
8      config: {
9        policies: [],
10        middlewares: [],
11      },
12    },
13  ],
14};
15
16// Path: ./src/api/hello/controllers/hello.ts
17import { factories } from '@strapi/strapi';
18
19export default factories.createCoreController('api::hello.hello', ({ strapi }) => ({
20  async exampleAction(ctx) {
21    try {
22      ctx.body = 'ok';
23    } catch (err) {
24      ctx.body = err;
25    }
26  },
27}));