When Should You Use Path Variable and Query Parameter?

In this article, I’d like to show you what is a Path Variable and Query Parameter. And how you think and use those as best practice.

Query Parameter

If you are a web developer, you must have learned about how to transfer data using GET method as a most simple way. Imagine that you’re creating some social service. Then you have to control user list. Each user has own page. When you want to create this page for each user, you need to path some identified parameter to that page. You can achieve that using something like this kind of get parameter:

/users?id=123 # Fetch a user who has id of 123 

Then, you can get id variable in backend. This is a Query String how it works. (In this article, I don’t describe how it handle in a backend specifically)

Path Variable

But, in other way, you can use Path Variable as one of the passing data method. You can define like this:

/users/123 # Fetch a user who has id 123

In this case, you can pass 123 to backend. You can use path as a variable.

When should you use Path Variable, and how about Query Parameter?

As a best practice, almost of developers are recommending following way. If you want to identify a resource, you should use Path Variable. But if you want to sort or filter items, then you should use query parameter. So, for example you can define like this:

/users # Fetch a list of users
/users?occupation=programer # Fetch a list of programer user
/users/123 # Fetch a user who has id 123

Also, you can get side effects. You don’t have to define other URL and other query parameter to achieve basic CRUD functions.You change HTTP method depends on what you want to do.

/users [GET] # Fetch a list of users
/users [POST] # Create new user
/users/123 [PUT] # Update user
/users/123 [DELETE] # remove user

Yes! you could achieve almost of CRUD process without extra endpoint (Ex. users/crete ) or Query Parameter (Ex. users?action=create ). Finally you could make it simple and expectable.

Wrapping up

If you don’t follow it, you can definitely make API and it will work. But, it will complicate. And it will cause delay of development. To maximize efficiency of development, you should follow standard and best practice. And it will help other developer to understand and catch up quickly. You can check other best practice for RESTful API from reference links. Thank you!