APIs are the backbone of modern applications, enabling data exchange between different services. Laravel provides an easy and elegant way to create APIs, and integrating Basic Authentication makes them secure and restricted to authorized users. In this blog post, we’ll go step by step to create an API in Laravel that uses Basic Authentication.
By the end of this guide, you’ll know how to:
- Set up a Laravel project for APIs
- Secure your API using Basic Authentication
- Test your API with tools like Postman and cURL
Prerequisites
- Basic knowledge of PHP and Laravel
- Composer installed on your system
- Laravel installed
Step 1: Setting up a Laravel Project
If you don’t have a Laravel project yet, let’s create one. Open your terminal and run the following command:
composer create-project --prefer-dist laravel/laravel api-basic-auth
This command will create a new Laravel project named api-basic-auth
. Navigate into the project directory:
cd api-basic-auth
Now, start the Laravel server:
php artisan serve
Your Laravel development server will now be up and running at http://localhost:8000
.
Step 2: Create a Controller for Your API
We will create a controller that handles our API logic. To create a new controller, use the following Artisan command:
php artisan make:controller ApiController
This will generate a controller named ApiController
in the app/Http/Controllers
directory.
Now, open app/Http/Controllers/ApiController.php
and add the following code to handle a basic GET request:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiController extends Controller
{
public function getData()
{
return response()->json([
'message' => 'Hello, this is a protected API route',
'status' => 200,
]);
}
}
Here, we’re simply returning a JSON response with a message. We’ll secure this API route using Basic Authentication in the next steps.
Step 3: Define the API Route
Open routes/api.php
, where we’ll define our API route. Add the following code:
use App\Http\Controllers\ApiController;
Route::get('/data', [ApiController::class, 'getData'])->middleware('auth.basic');
This code registers a GET endpoint at /api/data
, which is secured by Laravel’s built-in auth.basic
middleware.
Step 4: Set Up Basic Authentication
Laravel uses the users
table and the email
field by default for Basic Authentication. The auth.basic
middleware will automatically check for valid credentials.
Ensure you have users in your users
table. If you’re using Laravel’s default setup, you can run the migration to create the users table:
php artisan migrate
You can create users via a seeder or the database itself. Here’s an example seeder you can use (database/seeders/DatabaseSeeder.php
):
use Illuminate\Support\Facades\Hash;
use App\Models\User;
User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => Hash::make('password'),
]);
Then run:
php artisan db:seed
This will create a user with the email john@example.com
and password password
. Now, you’re ready to test the Basic Authentication.
Step 5: Testing the API with Basic Authentication
Now that we have our API set up, let’s test it using Postman and cURL.
Testing with Postman
- Open Postman and create a new GET request.
- Set the URL to
http://localhost:8000/api/data
. - Under the Authorization tab, select Basic Auth.
- Enter the email and password of the user created earlier.
- Username:
john@example.com
- Password:
password

When you send the request, you should receive the following JSON response:
{
"message": "Hello, this is a protected API route",
"status": 200
}
Testing with cURL
Alternatively, you can test your API using cURL from the terminal:
curl -u john@example.com:password http://localhost:8000/api/data
This will return the same JSON response:
{
"message": "Hello, this is a protected API route",
"status": 200
}
Step 6: Customizing Basic Authentication
By default, Laravel’s auth.basic
middleware uses the email
field for authentication. If you want to customize this behavior (e.g., authenticate using a username
field), you can do so in your User
model.
Example: Customizing the Username for Authentication
In app/Models/User.php
, add the following method:
public function getAuthIdentifierName()
{
return 'username'; // Use 'username' instead of 'email'
}
Make sure to update the database and create users with a username
field instead of email
.
Step 7: Conclusion
In this guide, we covered how to create a basic API in Laravel secured by Basic Authentication. We walked through setting up routes, creating controllers, and testing the API using Postman and cURL.
Key takeaways:
- Laravel’s
auth.basic
middleware makes it easy to secure APIs. - You can easily customize the authentication logic by modifying the User model.
By securing your API, you ensure that only authorized users have access, adding an essential layer of protection to your web services.
Further Improvements
To enhance your API’s security, consider implementing:
- Laravel Sanctum: For token-based API authentication.
- Laravel Passport: For OAuth2.0 authentication and more advanced API security.
Both of these packages provide more robust API authentication mechanisms beyond Basic Authentication.
That’s it! You’ve successfully created a Laravel API with Basic Authentication.
Images
- Laravel Project Creation
- Postman API Testing
Feel free to copy and use this content