Json option in httpClient Symfony throw error

482 views Asked by At

I'm using httpClient on symfony and I'm calling an API I want to use the json option instead of using body but it won't work, when I use body and I type in json format everything work but I don't find it clean so I wan't to use the json option which work only with simple variables like json => ['var1' => 'value1, 'var2' => 'value2'...]

But as soon as I'm using arrays it won't work and i'm getting this error :

The type of the key "firstname" must be "int", "string" given.

See my code below

$procedure = $this->httpClient->request(
        'POST',
        "https://fakeurl.com",
        [
          'headers' =>
            [
              'Accept' => 'application/json',
              'Content-Type' => 'application/json',
            ],
          'auth_bearer' => "key",
          'json' => [
            "name" => "name",
            "description" => "description",
            "start"  => true,
            "members" => [
                "firstname" => $user->getFirstName(),
                "lastname" => $user->getLastName(),
                "email" => $user->getEmail(),
                "phone" =>"+3312345678",
                "fileObjects" => [
                  "file" =>$file['id']
               ]
             ]
          ]
        ]
      );
1

There are 1 answers

0
AudioBubble On

I just found the solution, the propriety "members" expect for an array so the correct way is this :

$procedure = $this->httpClient->request(
        'POST',
        "https://fakeurl.com",
        [
          'headers' =>
            [
              'Accept' => 'application/json',
              'Content-Type' => 'application/json',
            ],
          'auth_bearer' => "key",
          'json' => [
            "name" => "name",
            "description" => "description",
            "start"  => true,
            "members" => [[
                "firstname" => $user->getFirstName(),
                "lastname" => $user->getLastName(),
                "email" => $user->getEmail(),
                "phone" =>"+3312345678",
                "fileObjects" => [[
                  "file" =>$file['id']
               ]]
             ]]
          ]
        ]
      );