Advertisement
Google Ad Slot: content-top
Laravel Introduction to REST APIs
What is an API?
- API = Application Programming Interface.
- It allows different software systems to communicate with each other.
- Example: A mobile app calls a server’s API to get user data.
What is REST?
- REST = Representational State Transfer.
- It is an architectural style for designing APIs.
- REST APIs use HTTP methods to perform actions on resources.
- Resources are represented by URLs (endpoints).
📌 Example:
GET https://api.example.com/users
This fetches a list of users.
Key Principles of REST
- Stateless → Each request contains all info (server does not store session state).
- Client-Server Separation → Client (frontend) and server (backend) are independent.
- Uniform Interface → Same approach for accessing resources.
- Resource-Based → Everything (users, posts, products) is a resource, identified by a unique URL.
- Representation → Resources can be returned in JSON, XML, etc. (JSON is most common).
REST API HTTP Methods
Method |
Purpose |
Example |
|---|---|---|
GET |
Retrieve resource(s) |
|
POST |
Create new resource |
|
PUT |
Update entire resource |
|
PATCH |
Update partial resource |
|
DELETE |
Remove resource |
|
API Resource Controllers
For API-only routes (no create, edit):
php artisan make:controller ProductController --api
This will create app/Http/Controllers/ProductController.php. with index,store,show,update,destroy functions
class PostController extends Controller
{
public function index(){ // }
public function store(Request $request){ // }
public function show(string $id){ // }
public function update(Request $request, string $id){ // }
public function destroy(string $id){ // }
}