Assignments On Class 29: Working with APIs - Part 1
Here are some assignments on working with APIs in PHP, along with their solutions.
Assignment 1: Basic API Request
Task:
1. Choose a public API (e.g., OpenWeatherMap API).
2. Write a PHP script that sends a GET request to the API to fetch weather data for a specific city.
3. Display the city's name, temperature, and weather description.
Example API URL (OpenWeatherMap):
bash
Copy code
https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}
Solution
php
Copy code
<?php
// API details
$city = "London";
$apiKey = "your_api_key"; // Replace with your actual API key
$url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric";
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
// Decode the JSON response
$data = json_decode($response, true);
// Check if the city was found
if (isset($data['main'])) {
echo "City: " . $data['name'] . "<br>";
echo "Temperature: " . $data['main']['temp'] . " °C<br>";
echo "Weather: " . $data['weather'][0]['description'] . "<br>";
} else {
echo "City not found.";
}
}
// Close the cURL session
curl_close($ch);
?>
Assignment 2: POST Request
Task:
1. Write a PHP script that sends a POST request to a public API (e.g., JSONPlaceholder) to create a new post.
2. Display the response containing the ID of the newly created post.
Example API URL (JSONPlaceholder):
arduino
Copy code
https://jsonplaceholder.typicode.com/posts
Solution
php
Copy code
<?php
// API URL
$url = "https://jsonplaceholder.typicode.com/posts";
// Data to be sent in the POST request
$data = [
'title' => 'My New Post',
'body' => 'This is the body of my new post.',
'userId' => 1
];
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string
curl_setopt($ch, CURLOPT_POST, true); // Specify POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Encode data as JSON
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json', // Set content type to application/json
]);
// Execute the request
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
// Decode the JSON response
$createdPost = json_decode($response, true);
echo "New post created with ID: " . $createdPost['id'];
}
// Close the cURL session
curl_close($ch);
?>
Assignment 3: Error Handling
Task:
1. Write a PHP script that retrieves data from a public API (e.g., JSONPlaceholder).
2. Implement error handling for both cURL errors and API response errors.
3. If the API returns an error message, display it.
Example API URL (JSONPlaceholder):
arduino
Copy code
https://jsonplaceholder.typicode.com/posts/9999
Solution
php
Copy code
<?php
// API URL for a non-existing post
$url = "https://jsonplaceholder.typicode.com/posts/9999";
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$response = curl_exec($ch);
// Check for cURL errors
if ($response === false) {
echo 'cURL Error: ' . curl_error($ch);
} else {
// Decode the JSON response
$data = json_decode($response, true);
// Check if the post exists
if (isset($data['id'])) {
echo "Post ID: " . $data['id'] . "<br>";
echo "Title: " . $data['title'] . "<br>";
} else {
// Display error message from API
echo "Error: Post not found.";
}
}
// Close the cURL session
curl_close($ch);
?>
Assignment 4: Query Parameters
Task:
1. Write a PHP script that makes a GET request to the Rick and Morty API (https://rickandmortyapi.com/api/character).
2. Allow the user to search for a character by name using query parameters.
3. Display the character's name, status, and species.
Solution
php
Copy code
<?php
// Get character name from query parameter
$characterName = isset($_GET['name']) ? urlencode($_GET['name']) : 'Rick';
// API URL
$url = "https://rickandmortyapi.com/api/character/?name=$characterName";
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
// Decode the JSON response
$data = json_decode($response, true);
// Check if characters were found
if (!empty($data['results'])) {
foreach ($data['results'] as $character) {
echo "Name: " . $character['name'] . "<br>";
echo "Status: " . $character['status'] . "<br>";
echo "Species: " . $character['species'] . "<br><br>";
}
} else {
echo "Character not found.";
}
}
// Close the cURL session
curl_close($ch);
?>
Conclusion
These assignments help students gain practical experience in making API requests using PHP. They can explore different APIs, practice error handling, and understand how to work with query parameters effectively.