How can you Build a Laravel REST API with Test-Driven Development

In Laravel development, to build a REST API with Test-driven development or TDD, you need to follow certain steps, starting with writing tests for defining the desired API behaviour, developing the API endpoints using the routing and controlling features of Laravel while running the tests continuously to ensure correct functionality. 

A RESTFul API is basically the architecture style for an API or Application program Interface that makes use of HTTP requests for accessing and using data. This data is used to PUT, GET, DELETE, and POST data types that refer to the updating, reading, deleting, and creating of operations concerning different resources. A RESTFul API conforms to the REST architecture’s constraints. 

Now, before getting started with the TDD in Laravel development, let’s understand what is REST API and what are its types. 

A REpresentational State transfer or REST API is the architectural style or you can say a set of concepts for an API or Application program Interface. REST API uses HTTP solicitations for accessing data used to PUT, GET, DELETE, and POST data types that allude to the refreshing, pursuing, erasing, and making of tasks concerning resources. The key benefit of REST API is that it offers high flexibility and enables you to use it in various ways and do more with the API. Here, in this post, you will get to know how to build Laravel REST API with TDD or Test-Driven Development without even opening a browser or Postman.

There are mainly 4 resource methods associated with REST API. 

  • GET – The GET resource method basically requests the server to get the requested data and then sends the same to you. 
  • POST – The POST method enables the server to create new entries in the database. 
  • PUT – The PUT method enables the server to update the entries in the database. 
  • DELETE – The DELETE request enables the server to delete the entries from the database. 

Now, let’s go through the steps to build a RESTFul API with TDD. 

Step 1: Install Laravel

Now, you must have enough knowledge about the Laravel framework before getting started with building a RESTFul API with TDD. So now, you will have to begin by developing secure Laravel APIs. Let’s develop a fresh Laravel web app by running this command below:

Install Laravel

Step 2: Install Passport

Next, you will have to add a passport library for building a RESTFul API with the framework.

Step 2: Install Passport

With this command, you can install the passport in your project’s vendor folder and can update the composer.json. This is the official Laravel package. 

Step 3: Configure Database

In the third step, you will need to configure your database in the ‘.env file.request’.

Step 3: Configure database

php artisan migrate

The service provider of passport registers its own directory for database migration, so you will need to migrate the database only after the package is installed. The passport migrations then will create these below tables in the database. Here, Laravel will also store OAuth2 access tokens and clients. 

Passport tables: 

  • Oauth_access_tokens
  • Oauth_clients
  • Oauth_auth_codes
  • Oauth_personal_access_clients
  • Oauth_refresh_tokens

Step 4: Generating The Keys now

Now you need to generate the keys using the below command

Step 4: Generating the keys now

This particular command will now create encryption keys for generating secure access tokens in your database.

Step 5: Register Passport In The Service Provider

Open the ‘config/app.php’ file and then update the provider array.

Step 5: Register passport in the service provider

Step 6: Update The User Model

Add a passport option to the ‘app/model/user.php’ that ships easily with plenty of helper method passport methods for authenticating the scopes and tokens of the users.

Step 6: Update the user model

Step 7: Call Passport Route

In order to register the routes to revoke and issue the access token, you will need to call the ‘passport::routes’ method in the boot method of the ‘AuthServiceprovider’. 

Open the ‘app/providers/AuthServiceProvider’ file and then update the content there as shown here.

Step 7: Call passport route

Step 8: Update The API Driver

For the app to get ready to be used, the token guard of the passport can be used to authenticate an incoming API request. Open the ‘config/auth’ configuration’ file and then set the driver option there to passport. Use this command

Step 8: Update the API driver
Step 9: Next You Will Need To Add The Authentication Methods In The Controller

Run this command

Step 9: Next you will need to add the authentication methods in the controller

This step is quite easy and all you need to do is add the ‘register’ and ‘authenticate’ methods to the controller. In the ‘authenticate’ method, you validate the input, then attempt a login, and then return that token after success. While in the ‘register’ method, you will validate the input, then create new users with that input, and then generate tokens for the users based on that. 

Step 10: – Generate Test Classes

Generate test classes using the command

Step 10: Generate test classes

In this new tests/feature/authTest folder, add the following methods 

One thing you must note down is that the tests should be independent and unique from each other and ideally from the database state. 

Now, run the ‘$phpunit’ or ‘$vendor/bin/phpunit’ if you already have it installed. If not then you can go through and check out the logs, fix them, and retest. It’s a beautiful TDD cycle.

Step 11: 

Now that you have the authentication working, you will need to add the same for CRUD. Begin by creating your migration ‘php artisan make:migration create_recipes_table’ and then run the migration. Add the model using the command ‘php artisan make:model xyz’ and then add this to your user model.  

Step 12: 

Now, you will need endpoints to manage your business products or services named here as ‘xyz’. First, you will have to create the controller using the command ‘php artisan make:controller xyzController’. Then edit the ‘routes/api.php’ file and add the ‘create’ endpoint. 

In the controller, now you will have to add the method: – 

Generate a feature test with the command ‘php artisan make:test xyzTest’ and edit the contents as required. 

Here, you will also have to create a method for handling the registering of the users and token generation. Then you use the tokens in the ‘testCreate()’ method. Also, note the benefit of the ‘RefreshDatabase’ option, which is a very convenient way to reset the database after every test. 

Now. you need to assert the status of the response so now run the command ‘$vendor/bin/phpunit’. 

If everything is ok, you get all green tests. 

But you still need to test the creation of xyz ( products or services you are offering ). For this, you can assert the xyz ( your business products or services ) count and then update your ‘testCreate’ method as below:  

You can proceed by filling the rest of your methods. Time to make some changes. And first in the ‘routes/api.php’. 

Next, you need to add your methods to your controller and update the controller class. 

Conclusion:

Hopefully, this blog gives you a detailed and step-by-step insight into how you can build a RESTFul API with TDD in Laravel development. Definitely, it is a much broader concept that this and this is just a part of it and can make things easier for you if you are trying to create a REST API for your Laravel project. To know more or to get your project built by Laravel experts, you can get in touch with GetAProgrammer, an award-winning software development company for bespoke Laravel development services.

Let’s talk!

We’d love to hear what you are working on. Drop us a note here & we’ll get back to you as soon as we can.

    icon

    *

    icon

    *

    icon

    *

    icon

    *

    Get Free Consultation