Welcome to this course about creating APIs in Laravel.
Let's dive into practice right away and start with a very simple example of building API by creating an endpoint for the categories list.
We have a new Laravel project, so first, we will create a new Model with Migration and Factory.
php artisan make:model Category -mf
database/migrations/xxx_create_categories_table.php:
public function up(): void{ Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); });}
app/Models/Category.php:
class Category extends Model{ use HasFactory; protected $fillable = ['name'];}
database/factories/CategoryFactory.php:
class CategoryFactory extends Factory{ public function definition(): array { return [ 'name' => fake()->words(asText: true), ]; }}
database/seeders/DatabaseSeeder.php:
use App\Models\Category; class DatabaseSeeder extends Seeder{ public function run(): void { Category::factory(10)->create(); }}
And run the migrations with the seed.
php artisan migrate --seed
Now, let's create the first API route endpoint to list all the categories. Let's start from the route. But, before being able to add API Routes we must run the install:api
artisan command. This command will install laravel/sanctum and will enable API Routes. After running this command we must add Laravel\Sanctum\HasApiTokens
trait to the User Model.
app/Models/User.php:
use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable{ use HasFactory, Notifiable; use HasApiTokens; // ...}
Now, we can add categories Route.
routes/api.php:
Route::get('/user', function (Request $request) { return $request->user();})->middleware('auth:sanctum'); Route::get('categories', [\App\Http\Controllers\Api\CategoryController::class, 'index']);
And let's create a Controller.
php artisan make:controller Api/CategoryController
In the Controller, we will return categories. By default, Laravel will take care to return JSON.
app/Http/Controllers/Api/CategoryController.php:
use App\Models\Category;use App\Http\Controllers\Controller; class CategoryController extends Controller{ public function index() { return Category::all(); }}
How do we launch the API from the browser or any client? Since this API route is public, you can launch it in the browser or any client.
First, let's see it in the browser. But before that, important part here. You would think that the route is /categories
, but in fact, because it is in the routes/api.php
, all routes have a prefix of /api
. This setting is set in the bootstrap/app.php
file.
bootstrap/app.php:
return Application::configure(basePath: dirname(__DIR__)) ->withProviders() ->withRouting( web: __DIR__.'/../routes/web.php', api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // }) ->withExceptions(function (Exceptions $exceptions) { // })->create();
As you can see, the filenames for the routes are set here. The prefix api
is set as a default value as a $apiPrefix
parameter.
After visiting the /api/categories
endpoint in the browser, we see the result in a JSON format.
But here is where I advise to use any API client of your choice. They format results more readably and provide more features like authenticating users.
Here is an example screenshot from the Postman and Insomnia clients.
This is the first step. It is easy to create an API endpoint and return the data if you don't need any more logic.
thank you povilas, please make more practical examples to get people going by doing. its the easiest way to start practising and learning new skills