0

I have review multiple instructions on URL-parameters which all suggest 2 approaches:

Parameters can follow / forward slashes or be specified by parameter name and then by parameter value. so either:

1)  http://numbersapi.com/42

or

2)  http://numbersapi.com/random?min=10&max=20

For the 2nd one, I provide parameter name and then parameter value by using the ?. I also provide multiple parameters using ampersand.

Now I have see the request below which works fine but does not fit into the rules above:

 http://numbersapi.com/42?json

I understand that the requests sets 42 as a parameter but why is the ? not followed by the parameter name and just by the value. Also the ? seems to be used as an ampersand???

Tartaglia
  • 949
  • 14
  • 20

1 Answers1

1

From Wikipedia:

Every HTTP URL conforms to the syntax of a generic URI. The URI generic syntax consists of a hierarchical sequence of five components:

URI = scheme:[//authority]path[?query][#fragment]

where the authority component divides into three subcomponents:

authority = [userinfo@]host[:port]

This is represented in a syntax diagram as:

Syntax diagram

As you can see, the ? ends the path part of the URL and starts the query part.

The query part is usually a &-separated string of name=value pairs, but it doesn't have to be, so json is a valid value for the query part.

Or, as the Wikipedia articles says it:

  • An optional query component preceded by a question mark (?), containing a query string of non-hierarchical data. Its syntax is not well defined, but by convention is most often a sequence of attribute–value pairs separated by a delimiter.

It is also fairly common for request processors to treat a name=value pair that is missing the = sign, as if the it was name=.

E.g. if you're writing Servlet code and call servletRequest.getParameter("json"), it would return an empty string ("") for that last URL in the question.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Thank you so much Andreas for the elaborate explanation. This is very helpful. So the query part is always preceded by a ? but does not necessarily contain key value pairs but could just contain the value itself. In my example above, the number 42 is thus not a parameter but part of the path, right? – Tartaglia May 10 '20 at 18:01
  • @Tartaglia That is correct. In Spring, it's known as a `@PathVariable`. See e.g. [@RequestParam vs @PathVariable](https://stackoverflow.com/q/13715811/5221149), which shows you can do both at the same time. – Andreas May 10 '20 at 22:21