Assignments Of Class 30 - Working with APIs - Part 2

Rashmi Mishra
0

 

Assignments Of Class 30 - Working with APIs - Part 2

Objective

  • Consume external APIs: Learn how to fetch data from third-party APIs and integrate that data into PHP applications.
  • Build a simple RESTful API with PHP: Understand the fundamentals of creating your own API.

Outcomes

By the end of this class, students will be able to:

  • Successfully fetch and display data from external APIs in their PHP applications.
  • Create a basic RESTful API using PHP that can handle different HTTP requests.

1. Overview of APIs

  • API (Application Programming Interface): A set of rules that allows one piece of software to interact with another.
  • REST (Representational State Transfer): A common architectural style for APIs, utilizing standard HTTP methods (GET, POST, PUT, DELETE).

Key Concepts

  • HTTP Methods:
    • GET: Retrieve data from the server.
    • POST: Send data to the server to create a new resource.
    • PUT: Update an existing resource on the server.
    • DELETE: Remove a resource from the server.

2. Consuming External APIs

Step-by-Step Process

1.  Identify an API: Find a public API you want to consume (e.g., JSONPlaceholder, OpenWeatherMap).

2.  Make a GET Request: Use PHP's cURL or file_get_contents() to fetch data.

Example: Fetching Data with cURL

Here’s how to use cURL in PHP to consume an external API:

php

Copy code

$url = "https://jsonplaceholder.typicode.com/posts"; // Sample API endpoint

$ch = curl_init(); // Initialize cURL session

 

// Set cURL options

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string

 

$response = curl_exec($ch); // Execute cURL session

curl_close($ch); // Close the session

 

// Decode JSON response

$data = json_decode($response, true);

 

// Display data

foreach ($data as $post) {

    echo "Title: " . $post['title'] . "<br>";

    echo "Body: " . $post['body'] . "<br><br>";

}

Important Notes

  • Always check if the API response is successful (HTTP status code 200).
  • Handle errors gracefully.

3. Creating a Basic RESTful API with PHP

Step-by-Step Guide

1.  Set Up Your Environment: Ensure you have a local server environment (XAMPP, WAMP) with PHP.

2.  Create an API Directory: Create a folder named api in your project directory.

Example: Simple RESTful API

Here's a basic example of how to set up a RESTful API:

Directory Structure:

bash

Copy code

/api

   ── index.php

   └── db.php

db.php (Database connection simulation):

php

Copy code

<?php

$posts = [

    ["id" => 1, "title" => "First Post", "body" => "This is the first post."],

    ["id" => 2, "title" => "Second Post", "body" => "This is the second post."]

];

index.php (API endpoint):

php

Copy code

<?php

header("Content-Type: application/json"); // Set header for JSON response

include 'db.php'; // Include database file

 

$requestMethod = $_SERVER["REQUEST_METHOD"]; // Get request method

 

switch ($requestMethod) {

    case 'GET':

        echo json_encode($posts); // Return all posts

        break;

    case 'POST':

        // Handle POST request to create a new post

        $newPost = json_decode(file_get_contents("php://input"), true);

        $posts[] = $newPost; // Add new post to the array

        echo json_encode($newPost); // Return the new post

        break;

    // Additional cases for PUT and DELETE can be added here

    default:

        http_response_code(405); // Method not allowed

        echo json_encode(["message" => "Method Not Allowed"]);

        break;

}

Testing the API

  • Use tools like Postman or Insomnia to test your API.
  • Make GET and POST requests to your API to verify functionality.

Example Requests

1.  GET Request:

o    URL: http://localhost/your_project/api/index.php

o    Method: GET

o    Response: List of posts in JSON format.

2.  POST Request:

o    URL: http://localhost/your_project/api/index.php

o    Method: POST

o    Body:

json

Copy code

{

    "id": 3,

    "title": "Third Post",

    "body": "This is the third post."

}

o    Response: Newly created post in JSON format.


Conclusion

  • APIs are powerful tools for enabling interactions between different software systems.
  • Understanding how to consume external APIs and create your own RESTful API is crucial for building modern web applications.

Homework

  • Task: Find an external API of interest, fetch data using PHP, and display it on a web page.
  • Create your own RESTful API that can handle at least two types of HTTP requests (GET and POST).

By mastering these concepts, students will be well-prepared to integrate and create APIs in their PHP applications, enhancing the functionality and interoperability of their projects.

4o mini

You said:

write some assignments with solutions

ChatGPT said:

ChatGPT

Here are some assignments focused on working with APIs in PHP, along with detailed solutions for each task.

Assignment 1: Fetch and Display Data from an External API

Task

Using the JSONPlaceholder API, write a PHP script that fetches and displays a list of users. The output should include the user's name, email, and address (street, city).

Solution

php

Copy code

<?php

// API endpoint

$url = "https://jsonplaceholder.typicode.com/users";

 

// Initialize cURL session

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

 

// Execute cURL session

$response = curl_exec($ch);

curl_close($ch);

 

// Decode JSON response

$users = json_decode($response, true);

 

// Display user information

foreach ($users as $user) {

    echo "Name: " . $user['name'] . "<br>";

    echo "Email: " . $user['email'] . "<br>";

    echo "Address: " . $user['address']['street'] . ", " . $user['address']['city'] . "<br><br>";

}

?>

Assignment 2: Create a Simple RESTful API

Task

Create a simple RESTful API that manages a collection of books. The API should support the following operations:

  • GET /api/books: Return a list of books.
  • POST /api/books: Add a new book to the collection.

Solution

Directory Structure:

bash

Copy code

/api

   ── index.php

   └── db.php

db.php (Simulated database):

php

Copy code

<?php

$books = [

    ["id" => 1, "title" => "1984", "author" => "George Orwell"],

    ["id" => 2, "title" => "To Kill a Mockingbird", "author" => "Harper Lee"]

];

index.php (API endpoint):

php

Copy code

<?php

header("Content-Type: application/json");

include 'db.php'; // Include simulated database file

 

$requestMethod = $_SERVER["REQUEST_METHOD"]; // Get request method

 

switch ($requestMethod) {

    case 'GET':

        echo json_encode($books); // Return all books

        break;

    case 'POST':

        // Handle POST request to add a new book

        $newBook = json_decode(file_get_contents("php://input"), true);

        $newBook['id'] = count($books) + 1; // Assign new ID

        $books[] = $newBook; // Add new book to the array

        echo json_encode($newBook); // Return the new book

        break;

    default:

        http_response_code(405); // Method not allowed

        echo json_encode(["message" => "Method Not Allowed"]);

        break;

}

Testing the API

1.  GET Request: Use Postman to send a GET request to http://localhost/your_project/api/index.php to retrieve the list of books.

2.  POST Request:

o    URL: http://localhost/your_project/api/index.php

o    Method: POST

o    Body:

json

Copy code

{

    "title": "The Great Gatsby",

    "author": "F. Scott Fitzgerald"

}

o    Response:

json

Copy code

{

    "id": 3,

    "title": "The Great Gatsby",

    "author": "F. Scott Fitzgerald"

}

Assignment 3: Error Handling in API Requests

Task

Modify the existing API from Assignment 2 to handle errors gracefully. If a user tries to access a book that doesn’t exist, the API should return a 404 error with a message.

Solution

Modified index.php:

php

Copy code

<?php

header("Content-Type: application/json");

include 'db.php'; // Include simulated database file

 

$requestMethod = $_SERVER["REQUEST_METHOD"]; // Get request method

$bookId = isset($_GET['id']) ? intval($_GET['id']) : null; // Get book ID from query parameters

 

switch ($requestMethod) {

    case 'GET':

        if ($bookId) {

            // Find the book by ID

            $book = array_filter($books, fn($b) => $b['id'] === $bookId);

            if ($book) {

                echo json_encode(array_values($book)[0]); // Return the specific book

            } else {

                http_response_code(404); // Not Found

                echo json_encode(["message" => "Book not found."]);

            }

        } else {

            echo json_encode($books); // Return all books

        }

        break;

    case 'POST':

        // Handle POST request to add a new book

        $newBook = json_decode(file_get_contents("php://input"), true);

        $newBook['id'] = count($books) + 1; // Assign new ID

        $books[] = $newBook; // Add new book to the array

        echo json_encode($newBook); // Return the new book

        break;

    default:

        http_response_code(405); // Method not allowed

        echo json_encode(["message" => "Method Not Allowed"]);

        break;

}

Testing the Error Handling

1.  GET Request for a Specific Book: Send a GET request to http://localhost/your_project/api/index.php?id=3. If the book does not exist, the response should be:

json

Copy code

{

    "message": "Book not found."

}

Assignment 4: Fetch Data from Multiple Endpoints

Task

Write a PHP script that fetches data from both the users and posts endpoints of JSONPlaceholder. Combine the data and display the user's name alongside their associated posts.

Solution

php

Copy code

<?php

// Fetch users

$userUrl = "https://jsonplaceholder.typicode.com/users";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $userUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$usersResponse = curl_exec($ch);

curl_close($ch);

$users = json_decode($usersResponse, true);

 

// Fetch posts

$postUrl = "https://jsonplaceholder.typicode.com/posts";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $postUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$postsResponse = curl_exec($ch);

curl_close($ch);

$posts = json_decode($postsResponse, true);

 

// Combine data and display

foreach ($users as $user) {

    echo "User: " . $user['name'] . "<br>";

    foreach ($posts as $post) {

        if ($post['userId'] == $user['id']) {

            echo "Post Title: " . $post['title'] . "<br>";

            echo "Post Body: " . $post['body'] . "<br><br>";

        }

    }

    echo "<hr>";

}

?>


These assignments and solutions will help students practice consuming and creating APIs in PHP, solidifying their understanding of how to interact with external services and build their own RESTful APIs.


Post a Comment

0Comments

Post a Comment (0)