Posting with Symfony 4.4 HTTP Client not working, status code 422

1.3k views Asked by At

I want to post info to external api but I get error 422 all the time. Geting info and authorization works fine. I'm using Symfony Http Client, authorization and headers are defined in framework.yaml for now.

Api documentation fragment:

curl "https://business.untappd.com/api/v1/locations/3/custom_menus"
-X POST
-H "Authorization: Basic bmlja0BuZXh0Z2xhc3MuY286OW5kTWZESEJGcWJKeTJXdDlCeC0="
-H "Content-Type: application/json"
-d '{ "custom_menu": { "name": "Wine selection" } }'

My service fragment:

public function customMenu(): int
{
    $response = $this->client->request(
        'POST',
        'https://business.untappd.com/api/v1/locations/'.$this->getLocationId().'/custom_menus',
        [
            'json' => [
                ['custom_menu' => ['name' => 'Wine selection']],
                ],
        ]
    );
2

There are 2 answers

0
Emilian On BEST ANSWER

Try to encode json "manualy", before send. Just like that

//$jsonData = '{ "custom_menu": { "name": "Wine selection" } }';
$jsonData = json_encode(["custom_menu" => ["name" => "Wine selection"]]);
 
$response = $client->request(
    'POST',
    'https://business.untappd.com/api/v1/locations/'.$this->getLocationId().'/custom_menus',
    [
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'body' => $jsonData,
    ]
);
1
MustaphaC On

There are an error and some missing parameters you didn't include:

  • The most important : Authorization (if you didn't add it to your framework.yaml file under 'http_client' parameter).
  • Your link ends with 'custom_menus' not 'menus'.
  • The content-type.

You can test this correction:

public function customMenu(): int
{
    $response = $this->client->request(
        'POST',
        'https://business.untappd.com/api/v1/locations/'.$this->getLocationId().'/custom_menus', //corrected '/custom_menus'
        [
            'auth_basic' => ['bmlja0BuZXh0Z2xhc3MuY286OW5kTWZESEJGcWJKeTJXdDlCeC0='], // To add
            'headers' => [ // To add
                'Content-Type' => 'application/json',
            ],
            'json' => [
                ['custom_menu' => ['name' => 'Wine selection']],
            ],
        ]
    );

    // .....
}