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.
Jump into concepts and practice - no test required
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.
Route::method('uri', [Controller::class, 'method']);
method with HTTP verbs like get, post, put, delete.uri is the URL path your API listens to, like 'users'.Route::get('users', [UserController::class, 'index']);
Route::post('users', [UserController::class, 'store']);
Route::put('users/{id}', [UserController::class, 'update']);
Route::delete('users/{id}', [UserController::class, 'destroy']);
This example sets up a GET API route at api/users. When called, it returns a JSON list of users.
<?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'] ]); } }
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.
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.
routes/api.php file?routes/api.php and usually return JSON data.response()->json(), which is correct. Others use wrong verbs or return types.routes/api.php:
Route::post('/user', function (Illuminate\Http\Request $request) {
return ['name' => $request->input('name'), 'age' => $request->input('age')];
});
What will be the JSON response if a POST request sends {"name": "Alice", "age": 30}?Route::get('/data', function () {
return response('Data');
});response('Data').$id parameter and returns JSON with the user's name including the ID.