rajiv tandon
rajiv tandon

Reputation: 33

Guzzle Post request with auth

First time I am using guzzle. Can anybody let me know How can I write Guzzle call for this request.

curl -X POST -u username:password -H "Content-Type: application/json" https://xyz/api/v1/accounts.json -d '{"user":{"username":"test","password":"xyz","first_name":"test","last_name":"test","email":"[email protected]","roles":["Administrator"]}}'

I am facing problem in -u of curl request.

I have written this code.
$response = $client->post($url, [
    'headers' => ['Content-type' => 'application/json'],
    'auth' => ['username:password'],
    'json' => [
        'username' => 'test'
    ],
]);
$results = $response->json();

I have tried this but unable to call API

Any Suggestion or Help.

Upvotes: 2

Views: 8939

Answers (1)

akshay
akshay

Reputation: 1161

As per the docs basic auth should be specified using array of two elements (login and password):

$client = new GuzzleHttp\Client();
$url = "//xyz/api/v1/accounts.json";
        $response = $client->post($url, [
            'headers' => ['Content-type' => 'application/json'],
            'auth' => [
                'test', 
                'xyz'
            ],
            'json' => [
                "username"=>"xyz",
                "password"=>"xyz",
                "first_name"=>"test",
                "last_name"=>"test",
                "email"=>"[email protected]",
                "roles"=>"Administrator"
            ], 
        ]);

Upvotes: 10

Related Questions