MaoStream
MaoStream

Reputation: 188

CloudMQTT API Guzzle

I have a problem with translating curl to guzzle request. In docs to create a user i just need to post:

$ curl -XPOST -d '{"username":"test", "password":"super_secret_password"}' -H         "Content-Type:application/json" -u "$CLOUDMQTT_USER:$CLOUDMQTT_PASSWORD"     https://api.cloudmqtt.com/user

In my project I cannot use curl, so i use guzzle:

$client = new Client();

$res = $client->post('https://api.cloudmqtt.com/user', ['auth' =>  ['xxx', 'xxx'], 'body' => ["username"=>"user", "password"=>"super_secret_password"]]);

And user is created, I can see new user on the users list on panel, but server is responsing with 500 when creating the user. What am I doing wrong? Maybe my guzzle request is wrong format? I have no idea

https://www.cloudmqtt.com/docs-api.html link to API

Upvotes: 0

Views: 251

Answers (1)

Samsquanch
Samsquanch

Reputation: 9146

This will match up your Guzzle request to the curl request, although I can't say for sure that will solve your 500 error:

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('https://api.cloudmqtt.com/user',
    [
        'auth' =>  ['xxx', 'xxx'],
        'body' => json_encode(
            [
                "username"=>"user",
                "password"=>"super_secret_password"
            ]
        )
    ]
);

The differences here include setting the Content-Type header and also encoding the body to json instead of an array (which may not have an effect here?).

EDIT: It looks like the json parameter will automatically set the header and json_encode the body for you:

$client = new Client();

$response = $client->post('https://api.cloudmqtt.com/user',
    [
        'auth' =>  ['xxx', 'xxx'],
        'json' =>
            [
                "username"=>"user",
                "password"=>"super_secret_password"
            ]
    ]
);

Docs

Upvotes: 1

Related Questions