How can I create a custom API endpoint with FindOne using slug?

default discord avatar
last month

In my pages collection I have a slug field which is generated on submission

name: 'slug', label: 'Slug', type: 'text', index: true, admin: { position: 'sidebar', }, hooks: { beforeValidate: [formatSlug(fieldToUse)], },

In the same collection, I created a custom REST endpoint for finding by slug, it obviously returns a single document for the respective slug, but since it uses payload.find from the Local API it returns a paginated response. Is there a way to do a findOne in the Local API. What is the best approach for this?

endpoints: [ { path: "/slug/:slug", method: "get", handler: async (req, res, next) => { const data = await payload.find({ collection: 'pages', where: {slug:{equals:req.params.slug}}, limit:1 }) if (data) { res.status(200).send({ data }); } else { res.status(404).send({ error: "not found" }); } }, }, ],

Oh my God, I'm just finding the documentation for using


in the default REST API which means I don't need my custom endpoint. That said the problem remains the same, I get a paginated response with payload's default where API also

  • default discord avatar
    last month

    Change the end of your custom endpoint with

    if ( === 0) {
      res.status(404).send({ error: "not found" });
    } else {
  • default discord avatar
    last month

    just send first element of array in the response, or if not exists 404

    i still think it's a good case for custom endpoint, so your end user won't need to manually create query on each request and less data in the response

  • default discord avatar
    last month

    That worked like a charm. Thank you. I still think payload Local API should add a findOne.

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!


Connect with the Payload Community on Discord



Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.