Strapi Custom Endpoints

Author : JaNakh Pon , September 05, 2021

Tags

Summary

In this article, we are going to create a simple strapi app with a custom endpoint and custom data response.

Read more about Strapi customization here.


Installation & setup

Firstly, let's create a strapi app with blog template using npx 😉:

  > npx create-strapi-app strapidemo --template blog

Since we are using the blog template, there will be a lot of folders under /api/ for api services.

However, we are going to add a new route for /api/article because we don't want to include every field from "article" to display in listing page.

And to do so, we need to go to "/api/article/config/routes.json" and add declare a new method under the routes[]:

routes.json
{
  "routes": [
    ,
    {
      "method": "GET",
      "path": "/customarticles",
      "handler": "article.customFind",
      "config": {
        "policies": []
      }
    },
    .
    .
    .
  ]
}

And now, let's add a handler function for "/customarticles" with a few certain fields ["id", "title", "description", "image"] that we might need for listing page:

article.js
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
  /**
   * Retrieve a record.
   *
   * @return {Object}
   */


  async customFind() {
    const entity = await strapi.query('article').model.fetchAll( {
      columns: ['id','title', 'description']
  });
    return sanitizeEntity(entity, { model: strapi.models.article });
  },
};

Finally, we need to allow the "customFind" function and make the "/customarticles" accessible to public.

And Let's do it by going to "Settings" => "Roles under Users & Permissions plugin" => "public" => and check "customfind" to true ☑️ under "ARTICLE".

Now, we can check the "/customarticles" route and its "Data response" via http://localhost:1337/customarticles 😉.

Source Code.