How to handle conflicting HTTP GET param - http

I'm designing a REST API that supports HTTP GET parameters. In most cases I only accept one value for a parameter. But how should I handle duplicate parameters?
For example, Stack Overflow accepts a GET param tab:
http://stackoverflow.com/?tab=hot
http://stackoverflow.com/?tab=featured
Duplicate parameters are allowed, passing both values is correct:
http://stackoverflow.com/?tab=hot&tab=featured
What should I do? Just go with the first value, thus silently ignoring other values (what SO does) or return an error stating only one value is allowed? In the latter case, what error should I return with what status code (409 Conflict, perhaps)?

I agree with VKSingla that this is a design decision, therefore there is no correct answer only opinions in this matter.
If you ask me I would make a 'strict' API and just throw an error (I would make sure that it is a clear error and not just a random code which doesn't help the user). I prefer this strict approach because if usercode is adding the same param twice it will likely be a bug somewhere in the users code. Revealing this bug as early as possible helps the user finding the bug asap.
If you choose to go with ignoring the other parameters then make sure that the user knows this behavior. For example document 'all duplicate parameters after the first will be ignored'. Undocumented 'magic behavior' like this can make code pretty damn hard to debug.

This is a design decision. Its your API design on how you want it to function.
If you choose to ignore any one , then the question is which one ?
So, it is simply a conflict. or else
your API can respond with combined data, but the request for that should be like this
https://stackoverflow.com/?tab=hot,featured
Also refer this question Extra Query parameters in the REST API Url

Related

Is a gRPC API returning "Any" a good idea?

I understand that there is no right or wrong answer here.
I see a gRPC API which returns "google.protobuf.Any". The job of the API is to take a param, which says what information needs to be fetched, and returns one of "n" things.
From an API design perspective, it is a good practice to define an API like this?
The other option would be to define a return message with "oneof" construct, which in my opinion tightly binds what the API can return.
Please let me know your thoughts.
Thanks for your time.
rpc getInformation(InfomationRequestParams) returns (google.protobuf.Any);
Returning Any from an API is common. oneof is preferred if you have a strict set of options that aren't added to often, but isn't appropriate if anyone may want to extend what is sent. The decision is similar to whether you choose to use an enum or a string in an API.
It does seem weird to not wrap the Any with a message, since generally there is type-independent information. But that's more specific to what your API actually provides and so may be fine as-is.

Determine if requester is an Ajax call and/or is expecting JSON (or another content type)

I have solved a problem with a solution I found here on SO, but I am curious about if another idea I had is as bad as I think it might be.
I am debugging a custom security Attribute we have on/in several of our controllers. The Attribute currently redirects unauthorized users using a RedirectResult. This works fine except when calling the methods with Ajax. In those cases, the error returned to our JS consists of a text string of all the HTML of our error page (the one we redirect to) as well as the HTTP code and text 200/OK. I have solved this issue using the "IsAjaxRequest" method described in the answer to this question. Now I am perfectly able to respond differently to Ajax calls.
Out of curiosity, however, I would like to know what pitfalls might exist if I were to instead have solved the issue by doing the following. To me it seems like a bad idea, but I can't quite figure out why...
The ActionExecutingContext ("filterContext") has an HttpContext, which has a Request, which in turn has an AcceptTypes string collection. I notice that on my Ajax calls, which expect JSON, the value of filterContext.HttpContext.Request.AcceptTypes[0] is "application/json." I am wondering what might go wrong if I were to check this string against one or more expected content types and respond to them accordingly. Would this work, or is it asking for disaster?
I would say it works perfect, and I have been using that for years.
The whole point use request headers is to be able to tell the server what the client accept and expect.
I suggest you read more here about Web API and how it uses exactly that technique.

Can't get the Sessions to work in webmatrix

I am trying to pass variables from one page to another using Sessions , but they don't seem to have effect. In the source page inside the razor syntax
Session["variable"] = "value";
And in the target page:
<p>#Session["variable"].ToString()</p>
but I get a server error
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Any suggestions would be most welcome........Thanks
I was only ever able to get this to work with casting:
<p>#(string)Session["variable"]</p>
Although it has been a long time since I have tried it with ToString() instead, I do explicitly remember my attempt to call a Session variable only successful with the casting option, although I have heard that ToString() should work. Either way, I always get it to work with casting.
That having been said, I feel it only right of me to warn you that if you are simply trying to pass data between pages, you shouldn't be using Session variables at all. Use hidden form fields, query strings, Url Data, or even cookies and/or databases before you do that.
I like to look at Session variables as something to quickly solve very special cases and only to be used very CAREFULLY. ALWAYS expect the value to be null and test its value before using it.
For help with the options for transferring data between web pages using WebMatrix, check out Mike Brind's very helpful site: http://www.mikesdotnetting.com/Article/192/Transferring-Data-Between-ASP.NET-Web-Pages <-- You'll want to bookmark this for now. It is right up the alley of what you are getting yourself into with WebMatrix.
If you still want to use the Session variable and casting doesn't work, the only other thing I can think that would cause the error is that the value you expect in Session["variable"] isn't what you think it is.
For the Record:
I was only trying to make a point when saying, "or even cookies and/or databases before you do that" Please do not use those options, as they are likely terrible in your case (also, cookies would just give you the same problems as Session variables, actually). In any case, it really all depends on how you are using the data and if you are always checking to make sure the value hasn't been cleared in the case of Session variables and/or cookies.

Using duplicate parameters in a URL

We are building an API in-house and often are passing a parameter with multiple values.
They use: mysite.com?id=1&id=2&id=3
Instead of: mysite.com?id=1,2,3
I favor the second approach but I was curious if it was actually incorrect to do the first?
I'm not an HTTP guru, but from what I understand there's not a definitive standard on the query part of the URL regarding multiple values, it's typically up to the CGI that handles the request to parse the query string.
RFC 1738 section 3.3 mentions a searchpart and that it should go after the ? but doesn't seem to elaborate on its format.
http://<host>:<port>/<path>?<searchpart>
I did not (bother to) check which RFC standard defines it. (Anyone who knows about this please leave a reference in the comment.) But in practice, the mysite.com?id=1&id=2&id=3 way is already how a browser would produce when a form contains duplicated fields, typically the checkboxes. See it in action in this w3schools example page. So there is a good chance that the whatever programming language you are using, already provides some helper functions to parse an input like that and probably returns a list.
You could, of course, go with your own approach such as mysite.com?id=1,2,3, which is not bad at all in this particular case. But you will need to implement your own logic to produce and to consume such format. Now you may or may not need to think about handling some corner cases by yourself, such as: what if the input is not well-formed, like mysite.com?id=1,2,? And do you need to invent yet another separator, if the comma sign itself can also be a valid input, like mysite.com?name=Doe,John|Doe,Jane? Would you reach to a point that you will use a json string as the value, like mysite.com?name=["John Doe", "Jane Doe"]? etc. etc.. Your mileage may vary.
Worth adding that inconsistend handling of duplicate parameters in the URL on the server is may lead to vulnerabilities, specifically server-side HTTP parameter pollution, with a practical example - Client side Http Parameter Pollution - Yahoo! Classic Mail Video Poc.
in your first approach you will get an array of querystring values but in second approach you will get a string of querystring values.
I guess it depends on technology you use, how it becomes convenient. I am currently standing in front of the same question using currency=USD,CHF or currency=USD&currency=CHF
I am using Thymeleaf and using the second option makes it easy to work, I can then request something like: ${param.currency.contains(currency.value)}. When I try to use the first option it seems it takes the "array" like a string, so I need to split first and then do contain, what leads me to a more mess code.
Just my 50 cents :-)

So why should we use POST instead of GET for posting data? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
How should I choose between GET and POST methods in HTML forms?
When do you use POST and when do you use GET?
Obviously, you should. But apart from doing so to fulfil the HTTP protocol, are there any reasons to do so? Less overhead? Some kind of security thing?
because GET must not alter the state of the server by definition.
see RFC2616 9.1.1 Safe Methods:
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
If you use GET to alter the state of the server then a search engine bot or some link prefetching extension in a web browser can wreak havoc on your site and (for example) delete all user data just by following links to your site.
There is a nice paper by the W3C about this: URIs, Addressability, and the use of HTTP GET and POST.
1.3 Quick Checklist for Choosing HTTP GET or POST
Use GET if:
The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
Use POST if:
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction
Because, if you use GET to alter state, Google can delete your stuff.
When do you use POST and when do you use GET?
How should I choose between GET and POST methods in HTML forms?
If you accept GETs to perform write operations then a malicious hacker could inject somewhere links to perform an unauthorized operation. Your user clicks on a link - and something is deleted from a database. Or maybe some amount of money is transferred away from the user's account if he's still logged in to their online banking.
http://superbank.com/TransferMoney?amount=1000&recipient=2342524
Send a malicious email with an embedded image referencing this link, and as soon as the document is opened, something funny has happened behind the scenes.
GET is limited by the length of URL the browser/server can handle. This used to be as short as 256 characters.
There is atleast one situation where you want a GET to change data on the server. That is when a GET returns data, and you need to record which data was given to a user and when it was given.
If you use complex data types then it must be in a POST it cannot be in a GET. For example testing a WCF web service in a browser can only be done when the contract uses simple data types.
Using GET and POST where it is expected helps to keep your program understandable.
When you use POST, you can see the information being "posted" in the address-bar of the web browser. This is [apparently] not the case when you use the GET method.
This article was somewhere on http://www.w3schools.com/ Once I've found the exact page it was on, I'll repost. :-)

Resources