Problem with content type in Magento Rest Api

When using the Rest Api of Magento with a POST request and you get following error: "Invalid data type. Check Content-Type." you must read my blogpost further because I know the answer :)

analyzing this

The source of this error is in app/code/core/Mage/Api2/Model/Request/Interpreter/Query.php:

if (!$this->_validateQuery($body)) {
    throw new Mage_Api2_Exception(
        'Invalid data type. Check Content-Type.',
        Mage_Api2_Model_Server::HTTP_BAD_REQUEST
    );
}
parse_str($body, $data);

with following method:

const URI_VALIDATE_PATTERN = "/^(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*'()\[\];\/?:@&=+$,])*$/";
protected function _validateQuery($query)
{
    return preg_match(self::URI_VALIDATE_PATTERN, $query);
}

So we see the body of the POST-request will get parsed if all signs are ok. That regex looks strange at first but is very easy, it basically allows this: A-Za-z0-9-_.!~*'()\[\];\/?:@&=+$, and a % sign with to hexadecimal numbers behind.

So what it does, it basically checks that the body is in this format: var1=value&var[test]=value2

When you receive an error, you have special characters in this and need to escape them. Special characters are for example a space (" ") or an umlaut ("äöü").

Next it continues to call parse_str() which will transfer this string into an array.

fixing this

Fixing this is very simple, you have a value in the POST-data which isn't correctly urlencoded. So you just need to urlencode() every value with special characters. This will replace a space with a plus-sign or for example a "#" with "%23".

Commentaires: