How to Build an API with Laravel and Sanctum

How to Build an API with Laravel and Sanctum

By ToolyBlog • 5 min read
Learn how to build a secure RESTful API in Laravel using Sanctum. This guide covers installation, authentication, routing, and testing your Laravel API.

APIs are the backbone of modern web and mobile applications. Whether you're building a single-page app (SPA), a mobile app backend, or a third-party developer API, Laravel Sanctum makes authentication simple and secure.

In this tutorial, you'll learn how to build a basic RESTful API in Laravel using Sanctum — complete with user registration, login, token-based authentication, and protected routes.


🔧 What is Laravel Sanctum?

Laravel Sanctum provides a featherweight authentication system for SPAs and simple token-based APIs. It is perfect when you need:

  • API tokens (for mobile or external apps)

  • Session-based authentication (for SPAs)

Unlike Laravel Passport, Sanctum is easy to set up and doesn't require OAuth2.


🚀 Step-by-Step: Building the API


✅ Step 1: Install Laravel


✅ Step 2: Install Sanctum

Then publish the Sanctum configuration:

Run the migrations:

✅ Step 3: Configure Sanctum

In app/Http/Kernel.php, add:

Also, ensure API middleware group includes auth:sanctum:


✅ Step 4: Create User Registration & Login Routes

Create the API routes in routes/api.php:


✅ Step 5: Protect Routes with Sanctum

Add a protected route that requires a token:

Use the token in the Authorization header:


✅ Step 6: Test Your API

Use Postman or Insomnia to test:

  1. POST /api/register – create a new user

  2. POST /api/login – receive an API token

  3. GET /api/profile – protected route (requires Bearer token)


🛡️ Extra Security Tips

  • Use throttle middleware to prevent brute force

  • Implement token revocation and logout endpoints

  • Use HTTPS in production for encrypted token transmission

  • Sanitize all input and validate extensively

📦 Sanctum vs Passport: When to Use Which?

Use Case Sanctum Passport
Mobile apps / SPAs ✅ Yes ✅ Yes
OAuth2 (third-party apps) ❌ No ✅ Yes
Lightweight API auth ✅ Yes ❌ No (heavier)
Simpler setup ✅ Yes ❌ No

✅ Final Thoughts

If you're building a modern API in Laravel in 2025, Sanctum is the go-to solution for fast, secure, and token-based authentication.

It integrates seamlessly with Laravel's core features, requires minimal setup, and is ideal for SPAs, mobile apps, and internal APIs.