Search code examples
restapi-design

Should I use a query parameter or separate endpoints for different data access levels?


I have an API endpoint for retrieving articles:

GET /articles

This endpoint can be accessed by both guests and administrators. The distinction lies in the data that can be retrieved.

For example, anyone can access this endpoint to show articles (by default it only show published articles):

GET /articles

However, if a query parameter is added:

GET /articles?withUnpublished

In this case, the client is required to provide an authentication token with the articles:read_unpublished scope.

Is this strategy ideal, or would it still be advisable to separate the endpoints? The response format remains the same, the only difference is in the accessible data.

I would like to know the community's opinion on whether this approach is suitable for my API design.


Solution

  • You should not split this URL into two or more if you are still returning the same resource, in your example it is `/articles'.

    But using a query parameter with a boolean type or just a parameter without any value is not a good practice. Because this approach is not extensible.

    For example, if you want to add a filter based on other criteria (e.g. "deleted" or "draft", or "not completed"), you need to add other query parameters with the boolean type, because it will be difficult to change the API that is being used right now. And that might look like this:

    /articles?withUnpublished&withDeleted&withUncompleted
    

    It looks kind of weird.

    Instead, you can create a filter as a query parameter, which will be whatever you want. And it will make your API more extensible.

    For example:

    /articles?status=UNPUBLISHED
    

    And if you want to extend the filter you just need to support another status or multiple statuses.

    /articles?status=DRAFT,DELETED
    

    Of course, the access verification method becomes more complicated, but the API becomes more flexible. It might make sense after all.