Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 479
rajiv tandon Avatar asked Feb 21 '26 23:02

rajiv tandon


1 Answers

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"
            ], 
        ]);
like image 197
akshay Avatar answered Feb 24 '26 13:02

akshay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!