Unable to use a new API (unless I make it public). Am I missing something?

Hello,

I am unable to use a custom API. It always returns 401. Here are the steps to reproduce:

  1. Generate a new API with npm run strapi generate
  2. Add a new route :
{
     method: 'GET',
     path: '/test',
     handler: 'test.exampleAction',
     config: {
       policies: [],
       middlewares: [],
     },
    }
  1. Call the new api using getFetchClient
const { get } = getFetchClient();
      const response = await get(`/api/test`);
  1. The call will return a 401 and redirect to the login page.

Note: If I create a custom plugin and define my route there it works perfectly. But with a simple api route (defined in /api) it does not work (unless I disabled auth altogether)

System Information
  • Strapi Version: v4.11.1
  • Operating System:
  • Database: MySQL
  • Node Version: v18.16.0
  • NPM Version:
  • Yarn Version:

Your route definition leaves the config.auth field undefined, which means you’ll get the default behaviour of requiring the user of the API endpoint to be authorized (either logged in or using an API token). However, if step 2 of your example occurs within the admin UI then getFetchClient should add the required token, automatically … unless you’ve added some ‘public user’ code to your admin UI. If you want the API endpoint to be available without authorization, just put auth:true in the route config object. But if you expected that the user would have been authorized and you’re still getting a 401 error, there might be some other problem. [You did remember to create a controller for the API, and you did remember to restart your server before trying to use the API endpoint?]

I found a tutorial here (How to Create a Custom API Endpoint in Strapi) that might be useful to you.

Thank you very much for your response :grinning:. I will git it a try and get back to you :+1: