What is best practice for search in API?
- GET + query parameters, example: GET /search?q=phone
- GET + parameters in body, example: GET /search {"query": "phone"}
- POST + parameters in body, example: POST /search {"query": "phone"}
What is best practice for search in API?
Don't include a body with a GET request. That's against the spec:
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
There are tradeoffs between the other two options. GET requests are cacheable, safe, and idempotent. They're also limited in size.
POST requests are not reliably cacheable, safe, or idempotent, and have no size limit. There's also more flexibility baked in - you can later create a filter resource on the server side in addition to returning the search result, and later searches can use that filter, possibly with a GET, although be careful if you allow caching and changes to the filter definition after it's created.
Looking at your specific example, supporting a single "search" endpoint can get messy pretty fast. If you haven't already, I would encourage you to consider other options.
POST requests are considered to change or create data on the server. GET is considered as a "Safe Method" which have no effect on the server database.
Since search requests do normally not change any data you should use a GET request. The limit is at least 2000 symbols (IE) so most of the times you are pretty safe.
POST
payload is up to the implementor, POST
requests are the swiss-army knife of HTTP operations which should be taken if none of the other, more specific operations are suitable. POST
is not only a create resource operation ... –
Hrutkay Definitely do 1, GET
using query parameters. It is much more likely to be cached.
If nothing in the data model changes on the server, your request should be GET. Server ops like logging is OK, but creation of a filter (as another answer suggested), as distinct from a query cache, say, is not.
© 2022 - 2024 — McMap. All rights reserved.