Geoff_S
Geoff_S

Reputation: 5107

Laravel API call doesn't pass payload

I'm trying to test an API post call in my laravel site, and I'm getting that the user doesn't exist because I believe the payload/body isn't being passed

If I test this manually in Swagger (with success) using the id and the body as

{
  "password": "passwordTest",
  "email": "[email protected]"
}

then the url shows as http://ip.address/login/?id=0 and the curl is

curl -X POST "http://ip.address/login/?id=0" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"password\": \"passwordTest\", \"email\": \"[email protected]\"}"

In my service file, it should be matching all the constructs but I dump it to the page and I get the error without a payload (the body)

Am I missing something?

AuthService.php

public function loginGetToken(){
    $password = "passwordTest";
    $email = "[email protected]";
    $id = "0";

    $payload = (object)[
        'password'=>(string)$password,
        'email'=>(string)$email
    ];

    $retval = $this->post('http://ip.address/login/?id='.$id,$payload);

    return $retval;
}

private function post($endpoint,$payload){
    //throws various exceptions:
    $result = $this->guzzleClient->request('POST', $endpoint, ['json'=>$payload]);
    $body = $result->getBody();
    return  json_decode($body);
}

Upvotes: 2

Views: 577

Answers (1)

whoacowboy
whoacowboy

Reputation: 7447

It's been a while, but I believe you need to tell Laravel that it is getting json.

private function post($endpoint,$payload){
   $options = [
        'headers' => [
            'Accept'       => 'application/json',
            'Content-Type' => 'application/json',
        ],
        'json' => $payload
    ];
    //throws various exceptions:
    $result = $this->guzzleClient->request('POST', $endpoint, options);
    $body = $result->getBody();
    return  json_decode($body);
}

Upvotes: 1

Related Questions