Problem creating a new GET request to findOne by slug

I’m facing a problem creating a new GET request for my posts.

I mostly followed this Youtube tutorial as reference.

I have posts in my api model for my blog, and each post has a slug. I tried to create a new GET request to findOne post by slug, while still keeping the findOne by id.

In post/config/routes.json, I created a new route findSlug:

{
      "method": "GET",
      "path": "/posts/:id",
      "handler": "post.findOne",
      "config": {
        "policies": []
      }
    },
    {
      "method": "GET",
      "path": "/posts/:slug",
      "handler": "post.findSlug",
      "config": {
        "policies": []
      }

Then I used the code in the Strapi docs under Concept > Controllers > Core Controllers, and edited it for my findSlug controller, under post/controllers/post.js:

async findSlug(ctx) {
    const { slug } = ctx.params;

    const entity = await strapi.services.post.findOne({ slug });
    return sanitizeEntity(entity, { model: strapi.models.post });
  },

Then I went to my admin dashboard to add the findSlug request under Role permissions for both public and authenticated users.

Restarted local server, and tested the new GET request using Insomnia, but I got “404 Not found”. My other GET requests /posts and /posts/:id all work fine.

So, what did I miss? Any advice and general pointers appreciated! :slight_smile:

I’m not an expert in how strapi works, but I don’t think you can do that!
The reason is the way of how routes are selected by a regex, there can be only one combination of /posts/:param, whatever that param will be. So, in your case post/config/routes.json will choose the first route, which is bound to :id and will give you the 404 response.

1 Like

@SorinGFS Is right, you actually defined two identical routes. So the second one is totally ignored.

Define the second route like this:

/posts/slug/:slug.

That way you will be able to access your posts by slugs

/posts/slug/my-test-slug-name

1 Like

Thanks @SorinGFS @sunnyson ! Will give it a try and report back! :slight_smile:

UPDATE:

It works!!! Thanks guys!

1 Like