Lecture Notes Of Class 11: Creating a Simple API in PHP
Objective:
In this class, we will learn how to create a simple RESTful API in PHP that can
handle GET and POST requests. We will also learn how to structure our API with
endpoints and parameters and how to return data in the JSON format, which is
the standard data format for APIs.
Introduction
to APIs
An API (Application Programming
Interface) allows different software applications to communicate with each
other. A REST API (Representational State Transfer API) is a popular type of
web API that uses standard HTTP methods like GET, POST, PUT, DELETE, etc., for
performing operations on resources.
In this class, we will focus on:
- Handling
GET and POST requests.
- Creating
simple API endpoints.
- Returning
data in JSON format, which is a lightweight, easy-to-read data format.
1.
Setting Up the Environment
Before starting with the code,
you need to have PHP installed on your system. If you’re using XAMPP or WAMP,
ensure that Apache and MySQL are running, but for this lesson, we won’t need
MySQL.
- Create
a folder in your htdocs (for XAMPP) or the root
directory of your server (for WAMP).
- Inside
this folder, create a new PHP file called index.php. This
file will serve as the entry point for our API.
2. Basic
Structure of a PHP API
A simple API typically starts by
listening to requests (GET, POST, etc.) and responding with data. In PHP, we
can use the $_SERVER superglobal to get the request method and determine what
kind of request is being made (GET, POST, etc.).
Example:
Basic API Structure
php
Copy code
<?php
// Set
the header to indicate that the response is JSON
header('Content-Type:
application/json');
// Check
the request method
$request_method
= $_SERVER['REQUEST_METHOD'];
// Handle
GET and POST requests
switch ($request_method)
{
case 'GET':
// Handle GET request
handle_get_request();
break;
case 'POST':
// Handle POST request
handle_post_request();
break;
default:
// Respond with an error message for
unsupported methods
echo json_encode(['message' => 'Method
Not Allowed']);
break;
}
function handle_get_request()
{
// Sample data to return (you can retrieve
data from a database in a real API)
$data = [
'id' => 1,
'name' => 'John Doe',
'email' => 'john@example.com'
];
// Return data in JSON format
echo json_encode($data);
}
function handle_post_request()
{
// Get raw POST data
$input_data = json_decode(file_get_contents('php://input'),
true);
// Sample validation: Check if name and
email are provided
if (!isset($input_data['name'])
|| !isset($input_data['email'])) {
echo json_encode(['message' => 'Missing
required fields']);
return;
}
// Simulate saving data and returning a
success response
$response = [
'message' => 'Data successfully
received',
'data' => $input_data
];
// Return the response in JSON format
echo json_encode($response);
}
?>
3.
Explanation of the Code
Header
Information
We set the header Content-Type:
application/json to tell the client that the response from this API will be in
JSON format.
Request
Method
The $_SERVER['REQUEST_METHOD']
retrieves the HTTP method (GET, POST, etc.) used in the request. We use a switch
statement to check the method and route it to the appropriate function:
- GET:
Used to retrieve data.
- POST:
Used to send data to the server.
GET
Request Handling
The handle_get_request() function
simulates fetching data. In a real application, this is where you would query a
database or another data source. Here, we are returning a sample user in JSON
format.
POST
Request Handling
The handle_post_request()
function retrieves the raw POST data sent by the client. It uses json_decode(file_get_contents('php://input'),
true) to parse the incoming JSON data into an associative array. This data is
then validated (checking if name and email are provided). If the data is valid,
we simulate saving it and return a success message along with the received data
in JSON format.
Error
Handling
If an unsupported HTTP method is
used, the API responds with a Method Not Allowed message.
4.
Testing the API
To test this API:
1. GET
Request: Open your browser and navigate to the following URL (replace localhost
with your server address if needed):
arduino
Copy code
http://localhost/your-folder-name/index.php
This will trigger the GET request
and return the sample data in JSON format.
2. POST
Request: You can use tools like Postman or cURL to send POST
requests to your API.
Using Postman:
o
Set the request type to POST.
o
Set the URL to:
arduino
Copy code
http://localhost/your-folder-name/index.php
o
In the Body section, select raw and
set the type to JSON. Then, add a sample JSON body:
json
Copy code
{
"name": "Jane Doe",
"email": "jane@example.com"
}
o
Send the request. You should receive a response
like:
json
Copy code
{
"message": "Data
successfully received",
"data": {
"name": "Jane Doe",
"email": "jane@example.com"
}
}
5.
Structuring the API with Endpoints and Parameters
In a more complex API, you would
structure the API with different endpoints and parameters. For example, you
could create endpoints like /users to handle user-related data.
Example:
Adding Parameters to GET Requests
You can handle URL parameters
(like ?id=1) in PHP using $_GET. Here’s an example where we handle a parameter
to fetch a specific user:
php
Copy code
function handle_get_request()
{
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
// Fetch the user from the database
using the user ID (simulation)
$data = [
'id' => $user_id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
echo json_encode($data);
} else {
// Return all users or a default
message
$data = [
'message' => 'No user ID
provided'
];
echo json_encode($data);
}
}
- If
you send a GET request to http://localhost/your-folder-name/index.php?id=1,
it will return the user data for ID 1.
6.
Conclusion
In this class, we’ve created a
simple API in PHP that:
- Handles
GET and POST requests.
- Returns
data in JSON format.
- Allows
basic validation and error handling.
This is just the beginning, and
in more complex APIs, you’ll be working with databases, authentication, error
handling, and more advanced techniques to make your API more robust.
Summary
of Key Concepts:
- GET
requests retrieve data from the server.
- POST
requests send data to the server.
- JSON is
the standard format for API responses.
- API
endpoints can be structured based on the resource they represent (e.g., /users,
/products).
Homework:
1. Create a
new endpoint for handling PUT requests to update data.
2. Modify
the POST request handling to save data in a file (simulate database storage).
4o mini
You said:
WRITE SOME ASSIGNMENTS FROM ABOVE
CONCEPT WITH STEP BY STEP SOLUTIONS with explanation
ChatGPT
said:
ChatGPT
Assignments
on Creating a Simple API in PHP
Here are some assignments based
on the concept of creating a simple API in PHP. These assignments will help
reinforce the concepts and give students hands-on experience.
Assignment
1: Building a Basic GET and POST API
Objective:
Create a simple PHP API that handles
both GET and POST requests. The API should return a sample user object on a GET
request and accept a user’s name and email on a POST request.
Instructions:
1. Create a
PHP file named index.php and set the header for JSON responses.
2. Handle GET
and POST requests to return or receive user data.
3. On GET,
return a user object in JSON format.
4. On POST,
accept name and email in the body of the request and return the received data
in JSON format.
Step-by-Step
Solution:
1. Create
the PHP File and Set Header: Start by creating index.php and ensure the
response is in JSON format.
php
Copy code
<?php
header('Content-Type:
application/json');
$request_method
= $_SERVER['REQUEST_METHOD'];
switch ($request_method)
{
case 'GET':
handle_get_request();
break;
case 'POST':
handle_post_request();
break;
default:
echo json_encode(['message' => 'Method
Not Allowed']);
break;
}
function handle_get_request()
{
$data = [
'id' => 1,
'name' => 'John Doe',
'email'
=> 'john@example.com'
];
echo json_encode($data);
}
function handle_post_request()
{
$input_data = json_decode(file_get_contents('php://input'),
true);
if (!isset($input_data['name']) || !isset($input_data['email']))
{
echo
json_encode(['message' => 'Missing required fields']);
return;
}
echo json_encode(['message' => 'Data
received', 'data' => $input_data]);
}
?>
2. Testing
the API:
o
GET Request: Open your browser and go to http://localhost/your-folder/index.php.
You should see the user data returned as JSON.
o
POST Request: Use Postman or cURL to send a
POST request with the following JSON body:
json
Copy code
{
"name": "Jane Doe",
"email": "jane@example.com"
}
The response will look like:
json
Copy code
{
"message": "Data
received",
"data": {
"name": "Jane Doe",
"email": "jane@example.com"
}
}
Assignment
2: Add URL Parameters to GET Request
Objective:
Enhance the API by adding support
for GET requests with URL parameters to retrieve data for a specific user based
on their ID.
Instructions:
1. Modify
the GET handler to accept an id parameter from the URL.
2. If an id
is provided, return the user data corresponding to that ID.
3. If no id
is provided, return an error message.
Step-by-Step
Solution:
1. Modify
the GET Handler to Accept URL Parameters:
php
Copy code
<?php
header('Content-Type:
application/json');
$request_method
= $_SERVER['REQUEST_METHOD'];
switch ($request_method)
{
case 'GET':
handle_get_request();
break;
case 'POST':
handle_post_request();
break;
default:
echo
json_encode(['message' => 'Method Not Allowed']);
break;
}
function handle_get_request()
{
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
$data = [
'id' => $user_id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
echo json_encode($data);
} else {
echo json_encode(['message' => 'User
ID not provided']);
}
}
function handle_post_request()
{
$input_data = json_decode(file_get_contents('php://input'),
true);
if (!isset($input_data['name']) || !isset($input_data['email']))
{
echo json_encode(['message' => 'Missing
required fields']);
return;
}
echo json_encode(['message' => 'Data
received', 'data' => $input_data]);
}
?>
2. Testing
the Modified API:
o
GET Request with ID: Go to http://localhost/your-folder/index.php?id=1
to see the user data for ID 1.
o
GET Request without ID: Go to http://localhost/your-folder/index.php
to get the error message: "User ID not provided".
Assignment
3: Handle Error Scenarios in API
Objective:
Extend the API to handle missing
data in both GET and POST requests, and provide appropriate error messages.
Instructions:
1. Modify
the POST request handler to check for required fields (name and email).
2. Modify
the GET request handler to check for a valid id parameter (it should be a
number).
3. Return
appropriate error messages when required fields or valid data are missing.
Step-by-Step
Solution:
1. Modify
the API for Error Handling:
php
Copy code
<?php
header('Content-Type:
application/json');
$request_method
= $_SERVER['REQUEST_METHOD'];
switch ($request_method)
{
case 'GET':
handle_get_request();
break;
case 'POST':
handle_post_request();
break;
default:
echo json_encode(['message' => 'Method
Not Allowed']);
break;
}
function handle_get_request()
{
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
// Validate the user ID (it should be
numeric)
if (!is_numeric($user_id)) {
echo json_encode(['message' => 'Invalid
ID, it should be numeric']);
return;
}
$data = [
'id' => $user_id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
echo json_encode($data);
} else {
echo json_encode(['message' => 'User
ID not provided']);
}
}
function handle_post_request()
{
$input_data = json_decode(file_get_contents('php://input'),
true);
if (!isset($input_data['name']) || !isset($input_data['email']))
{
echo json_encode(['message' => 'Missing
required fields: name or email']);
return;
}
echo json_encode(['message' => 'Data
received', 'data' => $input_data]);
}
?>
2. Testing
the Error Handling:
o
GET Request with Invalid ID: Go to http://localhost/your-folder/index.php?id=abc
to get the error message: "Invalid ID, it should be numeric".
o
POST Request with Missing Fields: Send a
POST request without the name or email fields, and it should return the error
message "Missing required fields: name or email".
Assignment
4: Add a PUT Endpoint to Update Data
Objective:
Add a PUT endpoint to update the
user data based on an ID parameter. The PUT request should accept a JSON body
containing the new name and email.
Instructions:
1. Add a new
endpoint for PUT requests.
2. The PUT
request should accept a user ID and new data (name and email).
3. Return
the updated data in JSON format.
Step-by-Step
Solution:
1. Add a PUT
Handler to the API:
php
Copy code
<?php
header('Content-Type:
application/json');
$request_method
= $_SERVER['REQUEST_METHOD'];
switch ($request_method)
{
case 'GET':
handle_get_request();
break;
case 'POST':
handle_post_request();
break;
case 'PUT':
handle_put_request();
break;
default:
echo json_encode(['message' => 'Method
Not Allowed']);
break;
}
function handle_get_request()
{
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
$data = [
'id' => $user_id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
echo json_encode($data);
} else {
echo json_encode(['message' => 'User
ID not provided']);
}
}
function handle_post_request()
{
$input_data = json_decode(file_get_contents('php://input'),
true);
if (!isset($input_data['name']) || !isset($input_data['email']))
{
echo json_encode(['message' => 'Missing
required fields']);
return;
}
echo json_encode(['message' => 'Data received',
'data' => $input_data]);
}
function handle_put_request()
{
parse_str(file_get_contents('php://input'),
$_PUT);
if (!isset($_PUT['id']) || !isset($_PUT['name'])
|| !isset($_PUT['email'])) {
echo json_encode(['message' => 'Missing
required fields: id, name or email']);
return;
}
$updated_data = [
'id' => $_PUT['id'],
'name' => $_PUT['name'],
'email' => $_PUT['email']
];
echo json_encode(['message' => 'Data
updated', 'data' => $updated_data]);
}
?>
2. Testing
the PUT API:
o
Use Postman or cURL to send a PUT request with the
following data:
json
Copy code
{
"id": 1,
"name": "Updated Name",
"email": "updated@example.com"
}
The response will be:
json
Copy code
{
"message": "Data
updated",
"data": {
"id": 1,
"name": "Updated
Name",
"email": "updated@example.com"
}
}
These assignments allow students
to understand and implement fundamental API operations using PHP, which is
crucial for building web applications.
4o mini
You said:
more
ChatGPT
said:
ChatGPT
Additional
Assignments on Creating a Simple API in PHP
Here are a few more assignments
that delve deeper into handling different HTTP methods, managing databases, and
applying better API design practices.
Assignment
5: Create a Basic CRUD API with MySQL
Objective:
Create a simple PHP API that
performs CRUD operations (Create, Read, Update, Delete) on a users table in a
MySQL database.
Instructions:
1. Set up a
MySQL database and create a users table with the following fields: id, name, email.
2. Implement
a POST endpoint for creating a new user.
3. Implement
a GET endpoint for retrieving user data by id.
4. Implement
a PUT endpoint to update a user’s name and email based on id.
5. Implement
a DELETE endpoint to remove a user based on id.
Step-by-Step
Solution:
1. Create
MySQL Database and Table:
sql
Copy code
CREATE
DATABASE api_example;
USE
api_example;
CREATE TABLE
users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
2. Create
the API PHP File (index.php):
php
Copy code
<?php
header('Content-Type:
application/json');
$request_method
= $_SERVER['REQUEST_METHOD'];
include('database.php');
// Include DB connection file
switch ($request_method)
{
case 'POST':
create_user();
break;
case 'GET':
get_user();
break;
case 'PUT':
update_user();
break;
case 'DELETE':
delete_user();
break;
default:
echo
json_encode(['message' => 'Method Not Allowed']);
break;
}
function create_user()
{
global $conn;
$input_data = json_decode(file_get_contents('php://input'),
true);
$name = $input_data['name'];
$email = $input_data['email'];
$query = "INSERT INTO users (name,
email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $query)) {
echo json_encode(['message' => 'User
created successfully']);
} else {
echo json_encode(['message' => 'Failed
to create user']);
}
}
function get_user()
{
global $conn;
$user_id = isset($_GET['id']) ? $_GET['id']
: null;
if ($user_id) {
$query = "SELECT * FROM users
WHERE id = $user_id";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
echo json_encode($user ? $user : ['message'
=> 'User not found']);
} else {
echo json_encode(['message' => 'User
ID not provided']);
}
}
function update_user()
{
global $conn;
parse_str(file_get_contents('php://input'),
$_PUT);
$user_id = $_PUT['id'];
$name = $_PUT['name'];
$email = $_PUT['email'];
$query = "UPDATE users SET name = '$name',
email = '$email' WHERE id = $user_id";
if (mysqli_query($conn, $query)) {
echo json_encode(['message' => 'User
updated successfully']);
} else {
echo json_encode(['message' => 'Failed
to update user']);
}
}
function delete_user()
{
global $conn;
parse_str(file_get_contents('php://input'),
$_DELETE);
$user_id = $_DELETE['id'];
$query = "DELETE FROM users WHERE id =
$user_id";
if (mysqli_query($conn, $query)) {
echo json_encode(['message' => 'User
deleted successfully']);
} else {
echo json_encode(['message' => 'Failed
to delete user']);
}
}
?>
3. Database
Connection (database.php):
php
Copy code
<?php
$conn = mysqli_connect('localhost',
'root', '', 'api_example');
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
4. Testing
the API:
o
Create User (POST): Send a POST
request with the body:
json
Copy code
{
"name": "John Doe",
"email": "john@example.com"
}
The response will be:
json
Copy code
{
"message": "User created
successfully"
}
o
Get User by ID (GET): Send a GET
request to index.php?id=1. The response will be:
json
Copy code
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
o
Update User (PUT): Send a PUT request with the
body:
json
Copy code
{
"id": 1,
"name": "Jane Doe",
"email": "jane@example.com"
}
The response will be:
json
Copy code
{
"message": "User updated
successfully"
}
o
Delete User (DELETE): Send a DELETE
request with the body:
json
Copy code
{
"id": 1
}
The response will be:
json
Copy code
{
"message": "User deleted
successfully"
}
Assignment
6: Secure API with Basic Authentication
Objective:
Add basic authentication to your
PHP API so that only authorized users can access the endpoints.
Instructions:
1. Implement
a function that checks for a valid username and password in the request
headers.
2. Protect
the GET, POST, PUT, and DELETE endpoints by requiring authentication.
3. Return an
error message if the authentication fails.
Step-by-Step
Solution:
1. Modify
the API to Add Basic Authentication:
php
Copy code
<?php
header('Content-Type:
application/json');
$request_method
= $_SERVER['REQUEST_METHOD'];
// Define
valid username and password
$valid_username
= "admin";
$valid_password
= "password123";
//
Function to check if request is authenticated
function authenticate()
{
global $valid_username, $valid_password;
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
echo json_encode(['message' => 'Authorization
header missing']);
exit();
}
$auth = explode(' ', $headers['Authorization']);
if (count($auth) == 2 && base64_decode($auth[1]))
{
list($username, $password) = explode(':',
base64_decode($auth[1]));
if ($username == $valid_username
&& $password == $valid_password) {
return true;
}
}
echo json_encode(['message' => 'Authentication
failed']);
exit();
}
authenticate();
// Authenticate on every request
switch ($request_method)
{
case 'POST':
create_user();
break;
case 'GET':
get_user();
break;
case 'PUT':
update_user();
break;
case 'DELETE':
delete_user();
break;
default:
echo json_encode(['message' => 'Method
Not Allowed']);
break;
}
function create_user()
{
echo json_encode(['message' => 'Create
user endpoint reached']);
}
function get_user()
{
echo json_encode(['message' => 'Get user
endpoint reached']);
}
function update_user()
{
echo json_encode(['message' => 'Update
user endpoint reached']);
}
function delete_user()
{
echo json_encode(['message' => 'Delete
user endpoint reached']);
}
?>
2. Testing
Basic Authentication:
o
Successful Authentication: Use
Postman or cURL and set the Authorization header to Basic
YWRtaW46cGFzc3dvcmQxMjM= (this is the base64 encoding of admin:password123).
The API will respond successfully with the appropriate message.
o
Failed Authentication: If you
send the request without the correct Authorization header or invalid
credentials, the API will return:
json
Copy code
{
"message": "Authentication
failed"
}
Assignment
7: Create a Paginated GET API
Objective:
Implement pagination for a GET request
that retrieves a list of users from the database.
Instructions:
1. Modify
the GET endpoint to accept page and limit parameters to control the pagination.
2. Retrieve
the corresponding set of users from the database.
3. Return
the users in JSON format along with the pagination metadata (e.g., total_users,
total_pages).
Step-by-Step
Solution:
1. Modify
the GET API to Handle Pagination:
php
Copy code
function get_user()
{
global $conn;
// Get pagination parameters
$page = isset($_GET['page']) ? (int)$_GET['page']
: 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit']
: 5;
$offset = ($page - 1) * $limit;
// Get total number of users for pagination
metadata
$result = mysqli_query($conn, "SELECT
COUNT(*) AS total FROM users");
$total_users = mysqli_fetch_assoc($result)['total'];
$total_pages = ceil($total_users / $limit);
// Retrieve users for the current page
$query = "SELECT * FROM users LIMIT $offset,
$limit";
$result = mysqli_query($conn, $query);
$users = mysqli_fetch_all($result,
MYSQLI_ASSOC);
// Return users and pagination metadata
echo json_encode([
'users' => $users,
'pagination' => [
'current_page' => $page,
'total_pages' => $total_pages,
'total_users' => $total_users
]
]);
}
2. Testing
Paginated API:
o
Request: Send a GET request to index.php?page=1&limit=5.
The response will be:
json
Copy code
{
"users": [ ... ],
"pagination": {
"current_page": 1,
"total_pages": 3,
"total_users": 15
}
}
These assignments provide a more
hands-on experience with working with APIs in PHP, helping students understand
authentication, database interaction, and pagination techniques.
4o mini
You said:
WRITE 50 no of MCQs only FROM
ABOVE CONCEPT with explanation
ChatGPT
said:
ChatGPT
Here are 50 multiple-choice
questions (MCQs) based on the concepts of creating a simple API in PHP,
including database interaction, handling HTTP methods, authentication, and
more. Each question is followed by an explanation.
MCQs:
1. What does
the acronym "API" stand for?
o
a) Application Programming Interface
o
b) Application Process Interface
o
c) Advanced Programming Integration
o
d) Automated Process Interface
Answer: a)
Application Programming Interface
Explanation: API stands for Application Programming Interface, which is
a set of protocols for building and interacting with software applications.
2. Which
HTTP method is used to create a new resource in an API?
o
a) GET
o
b) POST
o
c) PUT
o
d) DELETE
Answer: b) POST
Explanation: POST is used to send data to the server to create a new
resource.
3. Which
HTTP method is used to retrieve data from a server?
o
a) POST
o
b) GET
o
c) PUT
o
d) DELETE
Answer: b) GET
Explanation: GET is used to request data from a specified resource.
4. In which
format does the API generally send the response data?
o
a) XML
o
b) HTML
o
c) JSON
o
d) CSV
Answer: c) JSON
Explanation: JSON (JavaScript Object Notation) is the most common format
for API responses because of its lightweight structure.
5. Which
HTTP method is used to update an existing resource?
o
a) GET
o
b) POST
o
c) PUT
o
d) DELETE
Answer: c) PUT
Explanation: PUT is used to update an existing resource.
6. Which
HTTP method is used to delete a resource?
o
a) POST
o
b) GET
o
c) PUT
o
d) DELETE
Answer: d)
DELETE
Explanation: DELETE is used to remove a resource from the server.
7. Which PHP
function is used to decode a JSON string?
o
a) json_encode()
o
b) json_decode()
o
c) json_parse()
o
d) json_parse_array()
Answer: b)
json_decode()
Explanation: json_decode() is used to convert a JSON string into a PHP object
or array.
8. In a
RESTful API, what does the endpoint "/users/{id}" typically refer to?
o
a) Create a new user
o
b) Retrieve a user by ID
o
c) Update all users
o
d) Delete all users
Answer: b)
Retrieve a user by ID
Explanation: "/users/{id}" is commonly used to retrieve a
specific user by their ID.
9. What is
the correct status code for a successful POST request?
o
a) 200 OK
o
b) 201 Created
o
c) 400 Bad Request
o
d) 404 Not Found
Answer: b) 201
Created
Explanation: The HTTP status code 201 indicates that a resource has been
successfully created.
10.
Which function in PHP is used to send a JSON
response?
o
a) json_send()
o
b) echo json()
o
c) json_encode()
o
d) send_json()
Answer: c)
json_encode()
Explanation: json_encode() is used to encode a PHP array or object into
a JSON string.
11.
Which HTTP status code indicates that a requested
resource was not found?
o
a) 200 OK
o
b) 201 Created
o
c) 404 Not Found
o
d) 403 Forbidden
Answer: c) 404
Not Found
Explanation: The 404 status code indicates that the requested resource
could not be found on the server.
12.
In a CRUD API, which operation corresponds to the
HTTP PUT method?
o
a) Create
o
b) Read
o
c) Update
o
d) Delete
Answer: c)
Update
Explanation: The PUT method is typically used to update an existing
resource.
13.
Which HTTP method should be used to retrieve all
users in an API?
o
a) GET
o
b) POST
o
c) PUT
o
d) DELETE
Answer: a) GET
Explanation: The GET method is used to retrieve data from the server.
14.
Which PHP function can be used to handle database
connections in PHP?
o
a) mysqli_connect()
o
b) mysqli_query()
o
c) mysql_connect()
o
d) mysql_query()
Answer: a)
mysqli_connect()
Explanation: mysqli_connect() is used to establish a connection to the
MySQL database.
15.
Which of the following is used to include an
external file in PHP?
o
a) include()
o
b) require()
o
c) both a and b
o
d) open()
Answer: c) both
a and b
Explanation: Both include() and require() are used to include external
files in PHP.
16.
What does a status code of 400 indicate in an HTTP
response?
o
a) OK
o
b) Created
o
c) Bad Request
o
d) Not Found
Answer: c) Bad
Request
Explanation: A status code of 400 indicates a bad request, often due to
missing or incorrect parameters.
17.
Which function is used to fetch all rows from a
MySQL result set in PHP?
o
a) fetch_row()
o
b) fetch_all()
o
c) mysqli_fetch_assoc()
o
d) mysqli_fetch_all()
Answer: d) mysqli_fetch_all()
Explanation: mysqli_fetch_all() fetches all rows from a result set as an
associative array or numeric array.
18.
What does the PUT method typically require in the
body of a request?
o
a) No data
o
b) The entire resource data to be updated
o
c) Only the resource ID
o
d) The URL of the resource
Answer: b) The
entire resource data to be updated
Explanation: PUT requests typically send the entire resource data that
should replace the existing resource.
19.
Which PHP function is used to retrieve the HTTP
request method?
o
a) $_SERVER['REQUEST_METHOD']
o
b) $_REQUEST_METHOD
o
c) $_SERVER['METHOD']
o
d) $_GET['METHOD']
Answer: a)
$_SERVER['REQUEST_METHOD']
Explanation: $_SERVER['REQUEST_METHOD'] returns the HTTP request method
(GET, POST, PUT, DELETE).
20.
Which status code is used to indicate that the
client is not authorized to access a resource?
o
a) 403 Forbidden
o
b) 404 Not Found
o
c) 401 Unauthorized
o
d) 500 Internal Server Error
Answer: c) 401
Unauthorized
Explanation: The 401 status code indicates that the client is not
authorized to access the requested resource.
21.
In a RESTful API, which status code should be
returned after deleting a resource?
o
a) 204 No Content
o
b) 200 OK
o
c) 201 Created
o
d) 400 Bad Request
Answer: a) 204
No Content
Explanation: 204 No Content indicates that the deletion was successful
but there is no content in the response.
22.
Which HTTP method should be used to submit form
data to a server in a secure way?
o
a) GET
o
b) POST
o
c) PUT
o
d) DELETE
Answer: b) POST
Explanation: POST is used for submitting data to the server, especially
for form submissions, as it is more secure than GET.
23.
Which of the following HTTP status codes indicates
a successful request?
o
a) 500 Internal Server Error
o
b) 200 OK
o
c) 401 Unauthorized
o
d) 403 Forbidden
Answer: b) 200
OK
Explanation: 200 OK is the standard HTTP status code for a successful
request.
24.
Which function is used in PHP to connect to a MySQL
database using the MySQLi extension?
o
a) mysqli_connect()
o
b) mysql_connect()
o
c) db_connect()
o
d) connection_open()
Answer: a)
mysqli_connect()
Explanation: mysqli_connect() is used to establish a connection to a
MySQL database.
25.
What does the json_encode() function in PHP do?
o
a) Decodes a JSON string into a PHP array
o
b) Encodes a PHP array or object into a JSON string
o
c) Sends a JSON response to the client
o
d) Converts a JSON object to an associative array
Answer: b)
Encodes a PHP array or object into a JSON string
Explanation: json_encode() converts PHP arrays or objects into a JSON
string.
26.
What is a key feature of RESTful APIs?
o
a) They are built using HTML forms
o
b) They follow the principles of stateless
communication
o
c) They cannot use HTTP methods
o
d) They only support XML data format
Answer: b) They
follow the principles of stateless communication
Explanation: RESTful APIs are stateless, meaning each request from the
client to the server must contain all the information needed to understand and
process the request.
27.
Which of the following is used for client-side
validation in an API?
o
a) PHP
o
b) JavaScript
o
c) MySQL
o
d) Apache
Answer: b)
JavaScript
Explanation: JavaScript is typically used for client-side validation in
web applications.
28.
Which of the following is NOT a valid HTTP request
method?
o
a) PUT
o
b) GET
o
c) CREATE
o
d) DELETE
Answer: c) CREATE
Explanation: There is no HTTP method called CREATE. The correct method
is POST for creating resources.
29.
Which status code represents a conflict when
processing a request?
o
a) 409 Conflict
o
b) 400 Bad Request
o
c) 201 Created
o
d) 500 Internal Server Error
Answer: a) 409
Conflict
Explanation: 409 Conflict is returned when there is a conflict with the
current state of the resource.
30.
In a paginated API response, which field represents
the current page number?
o
a) total_count
o
b) page
o
c) current_page
o
d) items_per_page
Answer: c) current_page
Explanation: current_page refers to the current page in a paginated
response.
31.
Which PHP function is used to run a SQL query
against the database?
o
a) mysqli_query()
o
b) mysql_query()
o
c) query_run()
o
d) execute_query()
Answer: a)
mysqli_query()
Explanation: mysqli_query() is used to execute SQL queries against the
database.
32.
Which type of authentication is commonly used for
APIs?
o
a) Token-based authentication
o
b) Cookie-based authentication
o
c) URL-based authentication
o
d) Session-based authentication
Answer: a)
Token-based authentication
Explanation: Token-based authentication is widely used in APIs to secure
endpoints.
33.
Which function is used to convert PHP objects into
JSON format?
o
a) json_parse()
o
b) json_encode()
o
c) json_decode()
o
d) serialize()
Answer: b)
json_encode()
Explanation: json_encode() is used to convert PHP objects into JSON
format.
34.
What does the $_GET superglobal array in PHP
contain?
o
a) Form data sent via POST
o
b) Form data sent via GET
o
c) Server environment variables
o
d) Session variables
Answer: b) Form
data sent via GET
Explanation: $_GET contains data sent via the GET method in HTTP
requests.
35.
Which of the following is used to fetch a single
row from a MySQL query result in PHP?
o
a) mysqli_fetch_assoc()
o
b) mysqli_fetch_array()
o
c) mysqli_fetch_row()
o
d) mysqli_fetch_object()
Answer: a)
mysqli_fetch_assoc()
Explanation: mysqli_fetch_assoc() fetches a result row as an associative
array.
36.
In PHP, which function is used to check whether a
connection to a MySQL database was successful?
o
a) mysqli_status()
o
b) mysqli_check()
o
c) mysqli_connect_error()
o
d) mysqli_connect()
Answer: c)
mysqli_connect_error()
Explanation: mysqli_connect_error() returns an error message if the
connection fails.
37.
What is the main advantage of using APIs in web
development?
o
a) APIs help automate HTML rendering
o
b) APIs allow different systems to communicate
o
c) APIs handle user authentication
o
d) APIs manage database connections
Answer: b) APIs
allow different systems to communicate
Explanation: APIs enable communication between different systems and
platforms.
38.
Which method should be used to handle form
submissions in PHP?
o
a) GET
o
b) POST
o
c) PUT
o
d) PATCH
Answer: b) POST
Explanation: POST is used to submit form data to the server securely.
39.
What is returned in the response when the HTTP
method is DELETE and the resource is successfully deleted?
o
a) 200 OK
o
b) 204 No Content
o
c) 500 Internal Server Error
o
d) 404 Not Found
Answer: b) 204
No Content
Explanation: 204 No Content indicates the resource was successfully
deleted and there is no response body.
40.
Which HTTP status code is returned when a request
requires authentication?
o
a) 401 Unauthorized
o
b) 403 Forbidden
o
c) 400 Bad Request
o
d) 404 Not Found
Answer: a) 401
Unauthorized
Explanation: 401 indicates that authentication is required to access the
resource.
41.
Which of the following is used to send parameters
in a GET request?
o
a) In the body of the request
o
b) In the URL
o
c) In the HTTP headers
o
d) In cookies
Answer: b) In
the URL
Explanation: In a GET request, parameters are sent as part of the URL in
the query string.
42.
Which function is used to fetch a single column
from a MySQL query result in PHP?
o
a) mysqli_fetch_column()
o
b) mysqli_fetch_object()
o
c) mysqli_fetch_assoc()
o
d) mysqli_fetch_row()
Answer: d)
mysqli_fetch_row()
Explanation: mysqli_fetch_row() retrieves a single row from a result
set, where each row is represented by an indexed array.
43.
What does the $_POST superglobal array in PHP
contain?
o
a) Form data sent via GET
o
b) Form data sent via POST
o
c) Server environment variables
o
d) Cookies
Answer: b) Form
data sent via POST
Explanation: $_POST contains data sent via the POST method in HTTP
requests.
44.
What is the first step in building a simple API in
PHP?
o
a) Set up the database connection
o
b) Define the routes and endpoints
o
c) Return data as JSON
o
d) Handle GET and POST requests
Answer: a) Set
up the database connection
Explanation: Setting up the database connection is usually the first
step to ensure you can interact with the data.
45.
Which function in PHP is used to insert a new
record into a MySQL database?
o
a) mysqli_insert()
o
b) mysqli_query()
o
c) mysqli_insert_query()
o
d) mysqli_prepare()
Answer: b)
mysqli_query()
Explanation: mysqli_query() is used to execute an SQL query, including
INSERT queries.
46.
Which is the main difference between PUT and PATCH
in HTTP methods?
o
a) PUT is for partial updates; PATCH is for full
updates
o
b) PUT is for full updates; PATCH is for partial
updates
o
c) PUT can only be used for file uploads
o
d) PATCH is not supported in REST APIs
Answer: b) PUT
is for full updates; PATCH is for partial updates
Explanation: PUT replaces the entire resource, while PATCH modifies part
of the resource.
47.
Which of the following is a method to protect APIs
from unauthorized access?
o
a) HTTP Status Codes
o
b) Authentication tokens
o
c) HTML Forms
o
d) Database queries
Answer: b)
Authentication tokens
Explanation: Authentication tokens (like JWT) are commonly used to
secure API access.
48.
Which is used to format PHP errors as JSON for API
responses?
o
a) json_encode()
o
b) json_error()
o
c) print_json()
o
d) json_format()
Answer: a)
json_encode()
Explanation: json_encode() is used to convert PHP errors into a JSON
format.
49.
Which status code is used when the server fails to
process the request due to an internal issue?
o
a) 500 Internal Server Error
o
b) 404 Not Found
o
c) 400 Bad Request
o
d) 502 Bad Gateway
Answer: a) 500
Internal Server Error
Explanation: 500 indicates that the server encountered an error while
processing the request.
50.
What type of data is typically sent in the body of
a POST request?
o
a) Data in the URL
o
b) Data in the query string
o
c) Form data or JSON
o
d) HTTP headers
Answer: c) Form
data or JSON
Explanation: POST requests commonly send data in the body, often as form
data or JSON.
