Custom api endpoint in strapi4 returning 404 not found error

107 views Asked by At

I am building a strapi application with javascript where I have to fetch some data from an external api. For my use case, I have to create a custom strapi api endpoint, which responds with the fetched data when hit. I do not want to create the api against any content type. I just want an endpoint for my above use case. Here is the code for the files I have been working with:

//.src/api/lpv-banner-data/controllers/lpv-banner-data.js

'use strict';

module.exports = {
  async fetchData (ctx, next){
    try{
      const data = await strapi.service("api::lpv-banner-data.lpv-banner-data").fetchData();
      console.log(data);
      ctx.body("data", data);
    }
    catch(err){
      ctx.badRequest("Post report controller error", err);
    }
  } 
};

//.src/api/lpv-banner-data/routes/lpv-banner-data.js

module.exports = {
  routes: [
    {
      method: 'GET',
      path: '/',
      handler: 'lpv-banner-data.fetchData', 
      config: {
        policies: [],
        middlewares: [],
      },
    },
  ],
  prefix: 'lpv-banner-data',
  controller: 'lpv-banner-data',
};
//.src/api/lpv-banner-data/services/lpv-banner-data.js


'use strict';
const axios = require('axios');

module.exports = {
    fetchData: async ()=> {
        try{
            const response = await axios.get(`https://api-endpoint`);
            const data = response.data;
            const propertyTypesData = await getPropertyTypes.json();
            return propertyTypesData;
        }catch(err){
            return err;
        }
    }
};

The external api gives a response. I have tried defining the entire fetch logic in the controller. But the results were same. I have given role permissions in the settings in the admin panel. There were no middlewares written for the above usecase. Note that I cannot write this api against any already built content types or cannot create a new content type. Is there a way to achieve this?

Postman api call

1

There are 1 answers

0
antokhio On

You have to use return in the controller instead of ctx.body