How to create a route on Strapi?

Hello,

I am trying to create a route.

On this link, the solution is the update the route.json file in the config folder in the api folder. The file (route.json) and the config folder don’t exist in my strapi project and it doesn’t work when I create them.

On this link, a solution is proposed by editing the js file existing in the routes folder itself present in the api folder.

I may have done a syntax mistake, because I don’t get results either.

'use strict';

/**
 * post router.
 */

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

module.exports = createCoreRouter('api::post.post', {
    only: ['find'],
    config: {
        find: {
          auth: false,
          policies: [],
          middlewares: [],
        }
    },
    method: GET,
    path: "/posts/:id/comments",
    handler: posts.comments.data
});

Help me please. Thank you.

Hi Mimitip,

You can create new routes for a given content-type by creating a file src/api/content-type/routes/whatever-you-like.js which could have a custom route like…

"use strict";

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

module.exports = {
  routes: [
    {
      method: "GET",
      path: "/content-type/custom-endpoint
      handler: "content-type.customendpoint",
    },
  ],
};

Which you can configure in the file /src/api/content-type/routes/content-type.js

"use strict";

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

module.exports = createCoreRouter("api::restaurant.restaurant", {
  //https://docs.strapi.io/developer-docs/latest/development/backend-customization/routes.html#configuring-core-routers
  config: {

    customendpoint: {
      // policies etc
    }
  },
});

And finally you can implement the controller for it in file src/api/content-type/controllers/whateveryoulike.js maybe like…

"use strict";

const { coreStoreModel } = require("@strapi/strapi/lib/services/core-store");

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

module.exports = createCoreController("api::restaurant.restaurant", ({ strapi }) => ({
  async customendpoint(ctx) {
    return await strapi.entityService.findMany("api::restaurants.restaurant");
  }
}));

Hope that helps.

Sorry, it didn’t work…

Thank you for answering. :slight_smile: