What is REST Queries in Payload cms

With the REST API, you can use the full power of Payload queries as well but they become a bit more unwieldy the more complex that they get.

Simple queries are fairly straightforward to write. To understand the syntax, you need to understand how Express and similar languages would go about parsing a complex URL search string into a JSON object. For example, the above simple query would be parsed into a string like this:

https://localhost:3000/api/posts?where[color][equals]=mint

This one isn’t too bad, but more complex queries get unavoidably more difficult to write as query strings. For this reason, we recommend to use the extremely helpful and ubiquitous qs package to parse your JSON / object-formatted queries into query strings for use with the REST API.

example:

import qs from ‘qs’

2

3const query = {

4 color: {

5 equals: ‘mint’,

6 },

7 // This query could be much more complex

8 // and QS would handle it beautifully

9}

10

11const getPosts = async () => {

12 const stringifiedQuery = qs.stringify(

13 {

14 where: query, // ensure that `qs` adds the `where` property, too!

15 },

16 { addQueryPrefix: true },

17 )

18

19 const response = await fetch(`http://localhost:3000/api/posts${stringifiedQuery}`)

20 // Continue to handle the response below…

21}

Leave a comment

Your email address will not be published. Required fields are marked *