I’m confused while designing API when to use slashes vs query strings, kindly explain with examples.
In general, it’s your preference. There is no hard fast rule as to when to do queries or when to not. But, if I was to give you a guideline, I would suggest that you use it with complex queries for searching, filtering or sorting. Here are some examples.
GET v1/pets -- get a list of pets
GET v1/pets/dogs -- get a list of dogs that are pets
GET v1/pets/cats -- get a list of cats that are pets
GET v1/pets/dogs/{id} -- get details for a dog with the id
GET v1/pets/dogs/names -- get a list of dog names
GET v1/pets/dogs/names/rex -- get a list of dogs that are named rex
GET v1/pets/dogs?name=rex -- get a list of dogs that are named rex
GET v1/pets/dogs?name=rex&age=3 -- get a list of dogs that are named rex & 3 years old
GET v1/pets?limit=20 -- get a list of the first 20 pets
GET v1/pets/dogs?color=brown -- get a list of dogs that are brown
You notice that in some simple cases such as names, you could use slashes or queries. But as the sorting, or searching became more complicated, queries are easier.
Hope this helps.
1 Like
thanks @Chris Hood for your kind replay
kindly if I get these options while taking the exam
GET v1/pets/dogs/names/rex --get a list of dogs that are named rex
GET v1/pets/dogs?name=rex --get a list of dogs that are named rex
what option shall I take ?
I would expect the first option is matching for a single object, where you’re passing a unique identifier
The second option with the query param is filtering
1 Like