form-encoded

From IndieWeb
(Redirected from x-www-form-encoded)


Form-encoded (shorthand for the content type: application/x-www-form-urlencoded ) is used with webmention and Micropub for receiving text fields in HTTP POST requests.

Some APIs (such as GitHub's OAuth API and early implementations of IndieAuth servers) return response data in form-encoded format as well, although that is generally becoming less common in favor of returning JSON responses from APIs instead.

Why

By using form encoded format in your APIs, you make it possible to build simple HTML web forms that exercise or use the API, without JS. This is a huge advantage over other methods such as XML RPC, or other formats like JSON.

More:

How

See how Webmention and Micropub do it.

Articles

Articles also recommending using of form encoded:

  • GOV.UK Representations are for the consumer

    The representations supported by an API for input will vary depending upon the complexity of the action, but where possible should include application/x-www-form-urlencoded to allow the construction of simple POST forms.

  • ...

Issues

Issues with Arrays

There appears to be some inconsistencies with how different parsers interpret arrays in form-encoded requests. Lets document those here.

PHP's parse_str parses properties ending in [] into an array. Otherwise, properties are single-valued (i.e. only the last value of a multi-valued property is retained).

php > parse_str("property=abc&property=def", &$result);
php > var_dump($result);
array(1) {
  ["property"]=>
  string(3) "def"
}
php > parse_str("property[]=abc&property[]=def", &$result);
php > var_dump($result);
array(1) {
  ["property"]=>
  array(2) {
    [0]=>
    string(3) "abc"
    [1]=>
    string(3) "def"
  }
}

Python's parse_qs method treats all properties as possibly multi-valued. It treats [] just like any other character

>>> parse_qs("property=abc&property=def")
{'property': ['abc', 'def']}

See Also