We have REST API's. I was trying to figure out the best way to do a Get with some special characters.
Currently, we have something like this: http://myhost.com/api/book/name=HarryPotter
The above URL works just fine, but gets complicated when certain special character's are included in the queryparam like '&' or '/', which will result in "No operation matching request path ... is found, HTTP Method : GET, ContentType : /, Accept : /,"
for ex: http://myhost.com/api/book/name=Dark/Thirty.
This will consider the '/' in 'Dark/Thirty' as an URL separator.
What is the best practice to be able to search such queries. Is using a JSON a better practice, if yes should I be using a GET or a POST? I believe it should be POST, as any slash in the query param is treated as an Url separator.
Meaning: even this would fail for GET. http://myhost.com/api/book/search={"name"="Dark/Thirty"}
And since this is actually not a POST i do not want to use it. As I am just listing out the books that meet my search criteria and not modifying or adding anything.
Any guideline in tackling similar problems?
The searchRecords API call says that "special characters like parentheses or comma in the value for a criteria, you must escape them using a back slash".
This link is a good read. In essence, if your Dark/Thirty
is an identifier (i.e. uniquely identifies a resource), then modify it (in a predictable pattern) so that it does not have the special characters; e.g., DarkThirty
or dark-thirty
. If it is, however, a search term, then you would be better served not to make it RESTful, but just pass it as a normal parameter; that's what they're for.
The difference between GET
and POST
is not what characters are in it, but what the objective is. GET
is for getting stuff: it should be free of side effects. A search, or retrieval of a page should be a GET
. POST
effects changes to a server. It is improbable you would need to make an operation that both requires sending more data than URL allows, and at the same time makes no changes on the server but simply renders a new page (allowing for exceptions like Shazam or TinEye).
Dealing with special characters in GET parameters is the job of URL encoding; if you have http://myhost.com/api/search?q=Dark%FThirty for a search, your site is no less good. There are two primary drivers for REST, as I understand them: human-friendliness and SEO-friendliness. Search does not need to be either. REST exists to identify resources, in my understanding; and search results from a query are not a resource.
To summarise, I'd go with:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With