Is it possible to query using a unique URL slug instead of the ID parameter, such as with the following example:
http://localhost:3100/api/articles/story-of-the-city?Yes
i have an example that might help here..
query
query($slug:Page_slug_operator) {
Pages(where: {slug: $slug}) {
docs {
title
description
}
}
}
variables
{ slug: { equals: '/your-slug' } }
I defined the Pages collection with a slug text field, then whatever else you'd like it to have
on the calling side, you'll want to get the first index of the result since it's technically getting back all the results. I would recommend making sure
unique
is set to true for the slug field
Awesome. Do you have a repository to check it maybe? π
nothing public, but i would experiment in
http://localhost:3000/api/graphql-playgroundto get your values right. i found this using the docs menu ultimately
Do you know is that task can be done by using rest api?
sure, you can form your graphql request as a rest call. don't necessarily need a middleman to handle that for you
the request body just needs the
query
and
variables
as the main properties. then you'll want the
Content-Type
to be
application/json
i'm using an auth token generated by one of my users in my users collection so my authentication header looks like
Authorization
set to
users API-Key <your-api-key>
Thanks!
Did it by using the custom endpoint:
https://payloadcms.com/docs/rest-api/overview#custom-endpointsNow I can request the article by using unique slug:
http://localhost:3000/api/articles/original-article-nameThat is awesome!!! Thank you very much
Would be awesome for future releases, a feature to query, not only based on id
Yeah... Perhaps something like that:
const Articles: CollectionConfig = {
slug: 'articles',
// a unique field by which the article should be searched
searchedBy: "slug",
labels: {
...
}
}
Just want to chime in here that you can do this out of the box with /api/your-collection-slug?where[slug][equals]=slug-to-find
Also I feel like I have to say, if you do use the local api you should use the βwhereβ property to filter docs at the db level instead of after you get them back π
Perfect!
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.