user1794918
user1794918

Reputation: 1149

GuzzleHttp\\Exception\\ClientException: Client error: `POST resulted in a `400 Bad Request` response:\n{"@context":"\\/api\\/contexts

I have built an API endpoint using this tutorial https://symfonycasts.com/screencast/api-platform. I have tested the API from the web interface and it accepts the input and stores the data. Now I am trying to send data from my application to the endpoint.

 curl -X POST "https://myweblocation.app/api/emergencyvisits" -H "accept: application/ld+json" -H "Content-Type: application/json" -d "{\"externalpatientid\":\"<patient-id>\",\"externalsiteid\":\"<site-id>\",\"poscode\":20,\"dos\":\"2020-02-28T00:10:52.416Z\",\"vistreason\":\"chest hurting bad\"}"

My code is this:

    $client = new Client(['verify' => 'my/pem/location.pem' ]);
    $siteid = $GLOBALS['unique_installation_id'];

    $body = [
        'externalpatientid' => $uuid,
        'externalsiteid' => $siteid,
        'poscode' => $pos_code,
        'dos' => $date,
        'visitreason' => $reason
    ];

    $headers = [
    'content-type' => 'application/json',
        'accept' => 'application/ld+json'
    ];

    $request = new Request('POST', 'https://myweblocation.app/api/emergencyvisits', $headers, json_encode($body));

    $response = $client->send($request, ['timeout' => 2]);

How to get Guzzle to programmatically produce the correct post to the server?

Upvotes: 0

Views: 8373

Answers (1)

CodyKL
CodyKL

Reputation: 1064

First of all, please don't post sensitive data like patient-id, site-id or your application URL.

Regarding your problem... In your curl command you use the param name vistreason but in your Guzzle request you use visitreason.

I've tested that with Postman and it returned a 500 Server error because the field vistreason can't be null.

Beside this I tested with Guzzle (6.x):

$client = new Client(['verify' => false]); // I deactivated ssl verification
$body = [
    'externalpatientid' => '<id from curl request>',
    'externalsiteid' => '<id from curl request>',
    'poscode' => 20,
    'dos' => '2020-02-28T00:10:52.416Z',
    'vistreason' => 'chest hurting bad'
];

$response = $client->request(
    'POST',
    '<your-server-api-url>',
    [
        'headers' => [
            'content-type' => 'application/json',
            'accept' => 'application/ld+json'
        ],
        'body' => json_encode($body),
    ]
);

var_dump(json_decode($response->getBody()->getContents()));
// Output seems to be a valid response with some data from the request.

Maybe there is something wrong with your cert for validation.

Note: I also highly recommend to implement a authentication in form of a token to interact with your API!

Upvotes: 2

Related Questions