APIs (Application Programming Interfaces) allow systems to communicate with each other. RESTful APIs are widely used in web applications to exchange data. In this lesson, you will learn how to consume RESTful APIs and build a simple REST API using PHP.
Lesson Outline
- Introduction to RESTful APIs
- Consuming RESTful APIs
- Building a Simple REST API with PHP
17.1 Introduction to RESTful APIs
What is a RESTful API?
- REST (Representational State Transfer) is an architectural style for designing APIs.
- Key Features:
- Stateless: Each request is independent and contains all necessary information.
- HTTP Methods: Standard HTTP methods are used for CRUD operations:
- GET: Retrieve data.
- POST: Create data.
- PUT: Update data.
- DELETE: Delete data.
- Resource-based: Data is represented as resources (e.g.,
/users
,/products
).
17.2 Consuming RESTful APIs
Fetching Data with file_get_contents
Example: Fetching Data from a Public API
Using cURL
to Consume APIs
What is cURL?
- cURL is a library in PHP for making HTTP requests.
GET Request with cURL
POST Request with cURL
17.3 Building a Simple REST API with PHP
Setting Up the Environment
- Create a new database
api_demo
and a tableusers
: - Insert sample data:
- Create a file
db.php
for database connection:
Creating the REST API
Step 1: API Endpoint Structure
/api/users
– GET (Retrieve all users)/api/users/:id
– GET (Retrieve a specific user)/api/users
– POST (Create a new user)/api/users/:id
– PUT (Update a user)/api/users/:id
– DELETE (Delete a user)
Step 2: Base API File (api.php
)
Step 3: Handle GET Requests
Step 4: Handle POST Requests
Step 5: Handle PUT Requests
Step 6: Handle DELETE Requests
Testing the API
- Use tools like Postman or cURL to test API endpoints.
- Example cURL commands:
- GET all users:
- POST a new user:
Activities and Exercises
- Consuming APIs:
- Fetch and display posts from the JSONPlaceholder API using cURL.
- Building APIs:
- Extend the
users
API to include user authentication (e.g., login).
- Extend the
- Validation:
- Add validation for user input (e.g., email format, required fields) in the POST and PUT endpoints.
Assignment
- Create a database
library
with tables:books
:id
,title
,author
.users
:id
,name
,email
.borrowed_books
:id
,user_id
,book_id
,borrowed_at
.
- Build an API with the following endpoints:
/api/books
(GET): Retrieve all books./api/users/:id/borrowed
(GET): Retrieve books borrowed by a user./api/borrow
(POST): Borrow a book.
Leave a Reply