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

Antonella's avatar

test API Sanctum POST it does not take the data

I am testing the following API with POST:

$data = [
        "A" => "a",
        "B" => "b",
        "filedJson" => ["a"=> "yes", "b"=> "no"]
    ];

    $response = $this->withHeaders([
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$user_tokens['[email protected]'],
    ])->post('/api/store',$data);
    dd($response);

unfortunately the answer I get

    Illuminate\Testing\TestResponse^ {#1867
 +baseResponse: Illuminate\Http\Response^ {#1944
  +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag^ {#1945
   #computedCacheControl: array:2 [
    "no-cache" => true
    "private" => true
   ]
   #cookies: []
   #headerNames: array:6 [
    "cache-control" => "Cache-Control"
    "date" => "Date"
    "content-type" => "Content-Type"
    "x-ratelimit-limit" => "X-RateLimit-Limit"
    "x-ratelimit-remaining" => "X-RateLimit-Remaining"
    "access-control-allow-origin" => "Access-Control-Allow-Origin"
   ]
   #headers: array:6 [
    "cache-control" => array:1 [
     0 => "no-cache, private"
    ]
    "date" => array:1 [
     0 => "Thu, 08 Oct 2020 10:30:27 GMT"
    ]
    "content-type" => array:1 [
     0 => "application/json"
    ]
    "x-ratelimit-limit" => array:1 [
     0 => 60
    ]
    "x-ratelimit-remaining" => array:1 [
     0 => 58
    ]
    "access-control-allow-origin" => array:1 [
     0 => "*"
    ]
   ]
   #cacheControl: []
  }
  #content: "{"error":{"A":["The A field is required."],"B":["The B field is required."]},"0":"Validation Error"}"
  #version: "1.1"
  #statusCode: 401
  #statusText: "Unauthorized"
  #charset: null
  +original: array:2 [
   "error" => Illuminate\Support\MessageBag^ {#1940
    #messages: array:2 [
     "A" => array:1 [
      0 => "The A field is required."
     ]
     "B" => array:1 [
      0 => "The B field is required."
     ]
    ]
    #format: ":message"
   }
   0 => "Validation Error"
  ]
  +exception: null
 }
 #streamedContent: null
}

it seems that no data passes to him, it seems absurd to me

if I test the thing with postman it only works that when I go to pass the data I call $ data it seems that nothing is passed to it

0 likes
1 reply
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

'Content-Type' => 'application/json', - you have to use postJson instead of post

->postJson('/api/store', $data);

or remove 'Content-Type' => 'application/json',

Please or to participate in this conversation.