Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Antonella's avatar

test API token Authorization:Bearer

I should test some bees with jetstream / Sanctum

to test bees with Insomnia just send the request as follows:

GET: http://laravel.test/api
Content-Type:application/json
Accept:application/json
Authorization:Bearer 37b3mWZ9BHc....LRZwbTnYBKtcQss

but if I have to test it from code? obviously with active middleware !

without token before i tested the api as follows from code

$ data = [
             "a" => "3",
             "b" => "2",
             "c" => ["a" => "yes", "b" => "no"],
         ];
$ response = $ this->post ('api/store', $ data);

with bearer token how do I send the $data request?

0 likes
4 replies
Antonella's avatar

i tried as follows but it doesn't work:

$token = 'lFMcWnzCWxzPF.....8UFjEcogbQKCO';
$response = $this->withHeaders(['Authorization'=>'Bearer '.$token])->get('/api');

gives me following error:

Expected status code 200 but received 302.

@frankielee

frankielee's avatar

@gianmarx

If you are excepting the response is in JSON format, please add this to the header

Example

$response = $this->withHeaders(['Authorization'=>'Bearer '.$token,
							    'Accept' => 'application/json'])//this line
->post ('api / store', $ data);

Also, you can dump the response before asserting the status.

2 likes

Please or to participate in this conversation.