Does the REST standard allow the use of query string?

Asked

Viewed 2,490 times

9

Most frameworks I know use URL parameters as follows:

/recurso/variavel

For example

/produtos/{nome}
/produtos/{categoria}

Some use between {} others <>, etc.

To differentiate the searches is usually passed beyond the value to filter, the field that will be filtered:

/recurso/campo/variavel

For example

/produtos/nome/{nome}
/produtos/categoria/{categoria}

But if you want to do more complex searches, filtering through more than one field, you create many routes, with several parameters:

/produtos/categoria/{categoria}/nome/{nome}/precoMinimo/{minPreco}/precoMaximo/{maxPreco}

If the user wants to search by category, minimum and maximum price, he has to create another route or use this passing the value of the name in white. I think it’s enough to understand how complex it is to do and maintain

The use of query string can spark, creating only one route for each resource, and adding only one condition for each field you want to use in the filter, whether it exists or not. This can also be implemented with loop from an array of parameter keys

Since it makes it easier, why not use it? REST standard does not allow or limit its use?

1 answer

13


REST is an architectural style that uses HTTP as a representative form, so it does both allow and supports the use of query strings.

Several libraries have options to include query strings during the request, the library Jersey Java for example uses the implementation javax.ws.rs.client.Webtarget, that has the definition of the method queryParam.

Since there is no standard to be followed regarding REST API mounting, each developer can define how they will use or assemble their API, whether or not using this feature.

Particularly, in projects, I follow the following rule:

  • The parameter is required to locate an entity?

    Treat the parameter as hierarchical part of the path (path) / URI

    Example: Search a user for a specific id GET usuarios/{id}

  • The parameter NAY is required to locate an entity, but provides important details that can help locate it?

    Treat the parameter as non-hierarchical part of the path, a complement to the request (query string)

    Example: Search all user notifications GET notificacoes/usuario/{id} / Search all user notifications for a specific system GET notificacoes/usuario/{id}?sistema=x

In the second example, it is possible to obtain a result only by informing the user, but if you want the notifications for a specific system, there is no problem, it is possible to use the same method and endpoint.

RFC 3986 - Path (hierarchical) and Query (non-hierarchical) definition (English))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.