Cover image for Testing an API with Laravel.

Testing an API with Laravel.

arielmejiadev profile image arielmejiadev ・1 min read

Hi, we are going to see some helpful methods to test an API.

Authenticate with API driver:

$this->actingAs(factory(User::class)->create(), 'api');

Hit an endpoint:

// instead of $this->post('/api/users', []);
// do this
$this->json('post', '/api/users' ,[])

An advantage of using this method is that at the background Laravel validate if a request require a json response (if request is an ajax request) or it requires an http request.

If you use the "json" method you can get the "validations/form request" messages as json, so it is easy to test what you need to return to an ajax/fetch request;

Get response

This is a very helpful method, to see the response in json format you can use:

$response = $this->json('get', '/api/users');

Thats all, I love short posts, you are welcome to comment, thanks for reading.

Posted on Jun 20 by:

arielmejiadev profile



Fullstack/Mobile developer, Laravel and Flutter enthusiast.


markdown guide