Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how use Http client (post request)

In pure php, I made a query of the following type:

        $post_data = http_build_query(['integrationModule' => json_encode($body)]);

        $header = [
            'Content-Type: application/x-www-form-urlencoded',
            'X-API-KEY: ' . $this->apiKey
        ];

        $opts = ['http' => [
            'method' => 'POST',
            'ignore_errors' => true,
            'header'    => $header,
            'content'    => $post_data
        ]];
        $ctx = stream_context_create($opts);
        $resp  = file_get_contents($this->url . '/api/v5/integration-modules/module-name/edit', false, $ctx);
        $data = json_decode($resp, true);

I received Success in response
I want to rewrite this to Http-client in Laravel:

  $res = Http::withHeaders([
            'Content-Type' => 'application/x-www-form-urlencoded',
            'X-API-KEY' => $this->apiKey,
        ])->post(
            $this->url . '/api/v5/integration-modules/module-name/edit',
            ['integrationModule' => json_encode($body)]
        );

but in response I get:
"success" => false "errorMsg" => "Parameter 'integrationModule' is missing"
What is my mistake?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your issue stems from the way the Laravel Http client is sending the data by default. Even though you’ve set the 'Content-Type' header to 'application/x-www-form-urlencoded', the post method sends the data as JSON unless specified otherwise. This means the integrationModule parameter isn’t being sent in the expected format, leading to the "Parameter ‘integrationModule’ is missing" error.

To fix this, you should use the asForm() method, which tells the Http client to send the data as URL-encoded form data. Here’s how you can modify your code:

$res = Http::withHeaders([
        'X-API-KEY' => $this->apiKey,
    ])
    ->asForm()
    ->post(
        $this->url . '/api/v5/integration-modules/module-name/edit',
        ['integrationModule' => json_encode($body)]
    );

By adding ->asForm(), the data will be sent with the 'application/x-www-form-urlencoded' content type, and your integrationModule parameter should be correctly received by the server.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading