Building Restful API in Laravel with Sanctum

What is REST APIs?

A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer.

REST is a set of architectural constraints, not a protocol or a standard. API developers can implement REST in a variety of ways.

For web developers, it’s important for us to authenticates our users via API Request. In Laravel itself, besides its full-stack development, we have many options on how to authenticate the requests. For example, we have the Laravel Passport package to do the authentication and OAuth processes. But, if you don’t want to use the OAuth feature that Passport offers, then the Laravel Sanctum may be a choice for you.

What is Laravel Sanctum?

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.

Sanctum provide two options. The first is the API Token Authentication, and the second is SPA Authentication.

HTTP Verbs Represent Actions

  • GET: retrieve resources
  • POST: create resources
  • PUT: update resources
  • DELETE: delete resources

Setting Up a Laravel Web Service Project

Let's begin to create our fresh laravel application for API Authentication using Laravel Sanctum.

This will create a new folder named LaravelSanctum containing our Laravel application. Now would be a good time to start the Laravel application to make sure everything is working as expected:

Installation and Setup of Laravel Sanctum

First of all, let’s add Laravel Sanctum to it. We need to install Laravel Sanctum into our application using Composer:

Next thing we need to do is publish laravel sanctum assets for that let's run following command:

This will create a sanctum.php file in the config directory, as well as the necessary migration files into the migrations directory.

Database Configuration

Let's configure database for our application. If you have don't have any database then create a new one. After creating database open .env file from root directory of your project. if .env file is missing from project then copy content from .env.example and create file. .env file defines many common environment variables

Replace * with your actual configuration in upper code.

After database configuration, run database migrations :

One very last thing we need to update User model before starting api development.

Open the app/Models/User.php file and add the following modifications:

Building Authentication API

First, let’s start with the basic endpoint scaffolding. Open routes/api.php and modify it.

Let’s start with registering for an account. In your terminal create the controller responsible for authentication by running the following command:

This will generate AuthController.php file in the app/Http/Controllers folder.

Open AuthController and add following code snippet below in it. This function will handle requests for register user :

Here first of all, we validate input data and make sure all required parameters are in request and check length of input data.

After validating data we store data into our database. Once user is created, we create personal access token for that user using createtoken() method. Here, we call the plainTextTokenproperty on the instance to access the plain-text value of the token.

Finally, we return a JSON response which contains our the generated token with it's type.

Now, let's add method for logging in user. For that add following code into AuthController :

In the above code, we are checking login credentials from request. if login credential match then we return new access token else we return message for that.

Let's add logout functionality to our API. Add below code into AuthController :

For the logout() function itself, we can just revoke the token. Then the token will automatically invalid if the client requested with revoked/deleted token.

Now our login functionality is created. Let’s create another endpoint which can only be accessed by authenticated users. We have already created route for that now open AuthController and add below code :

This code is pretty simple. We simply return the currently authenticated user name.

Restricting Routes to Only Authenticated Users

We have already assigned middleware to our user_name route like :

We can also assign middleware to route group For example :

Testing the API

For Running or Testing API application enter below command :

It will produce output like below :

Now we can test our API endpoints using any API testing tool like Postman or any other.


Share your thoughts

Ask anything about this examples