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

Shivers's avatar

CSFR Token Needed When Posting Through API?

I can't find a definitive answer on this one. I'm running into errors when trying to POST to an API (created through the api.php file). Taylor's video on API-driven development suggests that no additional authentication is needed when using an API.

The only middleware I'm seeing applied to the API routes are: 'api' => [ 'throttle:60,1', 'bindings', ]

I've tried both $.ajax() and vue-resource's this.$http.post() and either receive a 500 error or an 'unauthenticated' error. I can post through Postman using the api_token, but that shouldn't be necessary when using accessing the app directly, correct?

So, do I need to pass a CSFR token when posting to an API? Does anyone have an example of posting to a Laravel Spark API using a VueJS method? Taylor's video covers GET requests, but it doesn't get into POST.

0 likes
3 replies
Shivers's avatar
Shivers
OP
Best Answer
Level 1

Answered my own question-

Despite the question/answers I'm finding when Googling the issue, CSFR tokens are not necessary when posting to an API.

I went back through and recreated my Eloquent model, the store method in my controller using the Laravel article on the subject (https://laravel.com/docs/master/eloquent#inserting-and-updating-models). My API route posts to the controller@store. My Vue component has a method that uses this.$http.post() to post the data to that API route to create the record.

It should have been more straightforward than what I originally did, but I screwed something up along the way. So, if you're like me and you're stuck on posting data to an API using Laravel/Spark/VueJS, you do not need a hidden field to submit the CSFR- assuming you're posting to a route on the same domain.

This is my experience anyway.

douglas_quaid's avatar

@Shivers can you explain this a little further? Currently, I'm easily able to consume my own API when I'm logged in because a Spark token is passed in the ajax requests. However, when I'm logged out, I'm getting a 401 unauthorized status. Can you explain how I can get around this? I'd like to consume the API from my front end with Vue when I'm logged in as well as logged out.

willbrowning's avatar

Use axios.post or axios.put or whatever you need I had a similar issue with this.$http but works perfectly with axios.

Please or to participate in this conversation.