In API design, should I put restriction on the HTTP method in which request parameters are sent?

StackOverflow https://stackoverflow.com/questions/18971594

Pergunta

My API endpoint accepts POST requests.

I use ServletRequest.getParameter to get request parameter value. getParameter can find parameter value in either requested string or POST form body. Given such behaviour, my API user can send a POST request passing parameters like a GET request:

/callApi?paramA=123&paramB=123

Although, the API should accpet form values instead of URL parameters.

I do not see any problem with it.

But from a good design perspective, should my API report an error when user attempts to make such requests?

Foi útil?

Solução

Since this question is tagged under "REST", I will answer the question assuming that you consider REST, and specifically REST via HTTP as "good API design".

HTTP has a pretty clear definition of what a URI is. Above all other things, a URI should serve as an identifier. If your URI can change (and the query string is part of the URI), and have the same result, from a RESTful HTTP standpoint, this could indicate something is off.

In your example, /callApi?paramA=123&paramB=123 is the (partial) URI for your resource. If you can POST to /callApi with a different body and have the same effect, then that either means you have information that identifies your resource in the body of your request OR you have data (the query string) in your URI that serves a purpose other than identifying a resource (which is what a URI should do).

If you don't care about RESTful principles, then of course this may not be applicable. If that is the case you may want to retag the question. Regardless, treating a URI as an ID first and foremost can be helpful when it comes to questions like yours.

Outras dicas

My instinct says "yes it's fine" on the basis that your server-side code should handle security the same way, regardless of the HTTP verb used, or the manner in which data is passed. Avoiding SQL injection by scrubbing the input, would be one such example.

I'm not familiar with the class and method you described but for consistency, I suppose I would use the POSTed form data rather than the query string data, assuming you have any way of distinguishing between the two.

I would say it would be fine, since in the end when you get a parameter theres no default way to determine if its Query String or in the Body. You would have to check the Query String to see if the parameter is present in there and then act accordingly.

I would just make your documentation specify to do it in the body as opposed to the query string and try and keep the URL you submit to as lean as possible.

I found this useful when providing an answer.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top