3
  • Strapi Version: 5.0.2 Community
  • Operating System: Windows 11 Professional Version 23H2 (OS Build 22631.4249)
  • Database: sqlite
  • Node Version: v20.17.0
  • NPM Version: 10.8.3
  • Yarn Version: 1.22.22

I newly installed the Strapi using the command below and chose to create the sample data.

yarn create strapi

I published all the articles and double-checked both find and findOne permission has been granted to the Public role on Author data.

I used Google Chrome to query the Author records.

I can get ALL the Authors records through this URL: http://localhost:1337/api/authors

    {
        "data": [
            {
                "id": 1,
                "documentId": "j32zwfrmo0h7ed5fk51qb1is",
                "name": "David Doe",
                "email": "[email protected]",
                "createdAt": "2024-10-03T14:54:43.775Z",
                "updatedAt": "2024-10-03T14:54:43.775Z",
                "publishedAt": "2024-10-03T14:54:43.772Z",
                "locale": null
            },
            {
                "id": 2,
                "documentId": "d7tjdbzbakg83kgnxe7818fi",
                "name": "Sarah Baker",
                "email": "[email protected]",
                "createdAt": "2024-10-03T14:54:44.657Z",
                "updatedAt": "2024-10-03T14:54:44.657Z",
                "publishedAt": "2024-10-03T14:54:44.652Z",
                "locale": null
            }
        ],
        "meta": {
            "pagination": {
                "page": 1,
                "pageSize": 25,
                "pageCount": 1,
                "total": 2
            }
        }
    }

However, I cannot get the any individual record from URL below and it throws 404 not found error.

http://localhost:1337/api/authors/2

{
    "data": null,
    "error": {
        "status": 404,
        "name": "NotFoundError",
        "message": "Not Found",
        "details": {}
    }
}

I have no customization to this Author collection type.

The controller of the Gift collection ./src/api/author/controllers/author.ts is as below:

/**
 *  author controller
 */

import { factories } from '@strapi/strapi';

export default factories.createCoreController('api::author.author');

did I miss any step?

2 Answers 2

9

Try using the documentId prop value instead of id.

http://localhost:1337/api/authors/d7tjdbzbakg83kgnxe7818fi in your case.

Sign up to request clarification or add additional context in comments.

1 Comment

Stack overflow still useful :) Thank you it worked for me in Strapi V5
0
    import { factories } from '@strapi/strapi';
    
    export default factories.createCoreRouter('api::author.author');

Suppose the CoreRouter will generate routes for these actions:

  • GET /authors (find all authors)
  • GET /authors/:id (find one author)
  • POST /authors (create a new author)
  • PUT /authors/:id (update an author)
  • DELETE /authors/:id (delete an author)

However, it seems find one author is not enabled by default.


/**
 * author router.
 * .\src\api\author\routes\author.ts
 */

// Core Router
//import { factories } from '@strapi/strapi';
//export default factories.createCoreRouter('api::author.author');


export default {
  routes: [
    {
      method: 'GET',
      path: '/authors',
      handler: 'api::author.author.find',
      config: {
        auth: false,
      },
    },
    {
      method: 'POST',
      path: '/authors',
      handler: 'api::author.author.create',
      config: {
        auth: false,
      },
    },
    {
      method: 'PUT',
      path: '/authors/:id',
      handler: 'api::author.author.update',
      config: {
        auth: false,
      },
    },
    {
      method: 'DELETE',
      path: '/authors/:id',
      handler: 'api::author.author.delete',
      config: {
        auth: false,
      },
    },
    {
      method: 'GET',
      path: '/authors/:id',
      handler: 'api::author.author.findOne',
      config: {
        auth: false,
      },
    },
  ],
};
/**
 *  author controller
 *  .\src\api\author\controllers\author.ts
 */

import { factories } from '@strapi/strapi';

export default factories.createCoreController('api::author.author', ({ strapi }) => ({
  // Customize the findOne method
  async findOne(ctx) {
    const { id } = ctx.params;

    // Ensure the ID is numeric
    const authorId = parseInt(id, 10);
    if (isNaN(authorId)) {
      return ctx.badRequest('Invalid ID format');
    }

    // Fetch the author by ID using Strapi's db query API
    const author = await strapi.db.query('api::author.author').findOne({
      where: { id: authorId },
      populate: ['books'], // Populate related data if needed
    });

    if (!author) {
      return ctx.notFound('Author not found');
    }

    //return author;
        
    // You can add more custom logic here if needed
    // sanitizeOutput - exclude private fields from the response
    // This will prevent sensitive fields, like password, from being exposed in the response 
    const sanitizedEntity = await this.sanitizeOutput(author, ctx);
    return this.transformResponse(sanitizedEntity);
  },
}));

I use custom route and controller to solve this issue. If you have any better way to solve it, please let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.