DEV Community

Cover image for Testing an API with Laravel.
Ariel Mejia
Ariel Mejia

Posted on

Testing an API with Laravel.

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

Authenticate with API driver:

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

Hit an endpoint:

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

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');
dd($response->getContent());
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)