Laravel 10 is great for building APIs because it gives clean structure and many built-in tools. In this guide I explain every step for beginners, from installation to authentication using token system (Laravel Sanctum). I keep language simple so you can follow and make your first API quickly.
Prerequisites:
Make sure you have: PHP 8.1 or above, Composer installed, MySQL (or other DB), and basic terminal knowledge. Also create a new directory for your project and open it in code editor.
Step 1 — Create new Laravel project:
Run composer create-project laravel/laravel api-demo then go inside project folder and start server using php artisan serve. Now you can open app on local URL.
Step 2 — Configure database:
Open .env and set DB_DATABASE, DB_USERNAME, DB_PASSWORD. Save changes and test connection.
Step 3 — Create model and migration for resource (example: Post):
Create a Post model with migration. In migration add fields like title and content and timestamps. After that run database migration to create posts table.
Step 4 — Set fillable properties and factory if needed:
Open Post model and set fillable fields so mass assignment works. You may create a factory to seed test data for development.
Step 5 — Create API controller and add CRUD methods:
Create controller for API (resource or api controller). Add methods: index (list), store (create), show (single), update, destroy. Validate incoming data and return JSON responses with clear messages and HTTP status codes.
Step 6 — Use API Resources for clean JSON (optional but recommended):
Create a resource class to format JSON response. This helps keep API output consistent and small (send only required fields).
Step 7 — Add routes in routes/api.php:
Register apiResource routes to map controller methods to endpoints. Group protected routes later for authenticated endpoints.
Step 8 — Validation and error handling for beginners:
Always validate request data and return user-friendly validation messages. Use try-catch where external calls exist. For not found resources return 404 with message. For validation return 422 with errors. Keep messages simple and consistent for client.
Step 9 — Pagination and filtering (basic):
When listing resources use pagination for large data. Accept query parameters like page, per_page, search or filter fields and apply them in query so response stays small and fast.
Step 10 — Logging and environment separation:
Use Laravel logging for errors (storage/logs). Keep APP_ENV and debug settings correct in .env. Never enable debug on production.
Step 11 — Implement token authentication with Laravel Sanctum (simple explanation for beginners):
Install Sanctum package and publish its config and migration. Run migrations for sanctum tables. In config/auth set API guard or use default. In kernel or route middleware enable auth:sanctum where needed. Create login route which validates user credentials and issues token using $user->createToken('token-name')->plainTextToken. Return the token to client after login. For logout delete current access token or revoke tokens using $user->currentAccessToken()->delete or $user->tokens()->delete. Protect API routes by adding middleware auth:sanctum so only requests with valid Bearer token can access them. In client (Postman or app) set Authorization header as Bearer <token> for protected endpoints.
Step 12 — Testing API (Postman / Thunder Client):
Test all endpoints: list, create, show, update, delete. For protected routes first call login to get token then add Authorization header. Check responses and correct status codes. Also test invalid inputs to see validation messages.
Step 13 — Queues for heavy tasks:
If create or update needs heavy work (image processing, sending email), push to queue job instead of doing inside request. Use Redis or database queue and run queue worker with supervisor in production.
Step 14 — Caching and rate limiting:
Cache repeated responses or heavy queries using cache drivers (Redis). Add rate limiting to API routes to prevent abuse (limit per minute per IP or per user).
Step 15 — CORS and frontend access:
If frontend is separate, configure CORS in config/cors.php and allow specific origins. Keep Access-Control headers correct so browser requests work.
Step 16 — Security best practices:
Sanitize input, use prepared statements (Eloquent does this), avoid exposing sensitive data in JSON, use HTTPS in production, store secrets in .env not in code, limit token lifetime if needed, and use personal access tokens correctly.
Step 17 — Deploy checklist (basic):
Set correct APP_ENV, APP_KEY, and database config on server. Run composer install --no-dev, php artisan migrate --force, php artisan config:cache, route:cache and queue worker supervised by supervisor or systemd. Use queue and scheduler settings for production.
Step 18 — Common errors and quick fixes:
If migration fails check DB credentials. If 401 unauthorized on protected route check token header or sanctum config (stateful domains for SPA). If N+1 problem use eager loading (with relation). If slow queries add indexes and use explain to check query plan.
Step 19 — Next improvements (after basic API works):
Add API versioning, API documentation (Swagger or simple docs), request throttling, tests (feature tests using Laravel’s HTTP tests), and monitoring (Sentry, Bugsnag or log monitoring).