0
0
Laravelframework~5 mins

API routes in Laravel

Choose your learning style9 modes available
Introduction

API routes let your Laravel app respond to requests from other programs or devices. They help your app share data or actions in a simple way.

When you want to let a mobile app get or send data to your Laravel backend.
When building a single-page app that talks to Laravel for data updates.
When creating a public API for other developers to use your app's features.
When connecting your Laravel app with external services or websites.
When you want to separate web pages routes from data-only routes.
Syntax
Laravel
Route::method('uri', [Controller::class, 'method']);
Replace method with HTTP verbs like get, post, put, delete.
The uri is the URL path your API listens to, like 'users'.
Examples
Defines a GET API route to list users.
Laravel
Route::get('users', [UserController::class, 'index']);
Defines a POST API route to create a new user.
Laravel
Route::post('users', [UserController::class, 'store']);
Defines a PUT API route to update a user by ID.
Laravel
Route::put('users/{id}', [UserController::class, 'update']);
Defines a DELETE API route to remove a user by ID.
Laravel
Route::delete('users/{id}', [UserController::class, 'destroy']);
Sample Program

This example sets up a GET API route at api/users. When called, it returns a JSON list of users.

Laravel
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('users', [UserController::class, 'index']);

// UserController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        return response()->json([
            ['id' => 1, 'name' => 'Alice'],
            ['id' => 2, 'name' => 'Bob']
        ]);
    }
}
OutputSuccess
Important Notes

API routes are usually placed in routes/api.php file in Laravel.

API routes by default have the /api prefix and use the api middleware group.

Use JSON responses to communicate clearly with clients calling your API.

Summary

API routes let your app handle requests from other apps or devices.

Use HTTP verbs and URIs to define what your API does.

Keep API routes in routes/api.php and return JSON data.