Search code examples
typescriptbackendstrapiendpoint

How do I create a custom endpoint API in Strapi?


I recently started using Strapi. I would like to learn how to create my own custom APIs, I did everything according to the documentation, but when I go along my route, I get a 404 error. In the beginning, everything starts without errors, but along the way http://localhost:1337/api/index returns error 404. I did everything by https://strapi.io/blog/how-to-create-a-custom-api-endpoint-in-strapi but it doesn't work. Can you tell me, maybe I did something wrong or something was updated?

Controller

//path src/api/account/controllers/account.js

'use strict';

const {createCoreController} = require('@strapi/strapi').factories;

module.exports = createCoreController('api::account.account', ({strapi}) => ({

  async index(ctx, next) {
    ctx.body = 'Hello World!';
  },
  
}));

Routes

//path src/api/account/routes/account.js

'use strict';

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::account.account', {
  routes: [
    {
      method: 'GET',
      path: '/index',
      handler: 'account.index',
    },

  ],
});

Solution

  • Instead of '/index' in the path put '/account', and your route should be reachable at /api/account.