Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
44 views11 pages

Chapter 6

Chapter 6 of the document discusses APIs and external data handling, explaining the importance of APIs in software development, including interoperability, reusability, and security. It covers different types of APIs such as REST, SOAP, and GraphQL, detailing their characteristics and use cases. The chapter also provides guidance on building and consuming APIs in PHP, including handling requests, sending JSON responses, and making external API requests using cURL.

Uploaded by

agetachew97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views11 pages

Chapter 6

Chapter 6 of the document discusses APIs and external data handling, explaining the importance of APIs in software development, including interoperability, reusability, and security. It covers different types of APIs such as REST, SOAP, and GraphQL, detailing their characteristics and use cases. The chapter also provides guidance on building and consuming APIs in PHP, including handling requests, sending JSON responses, and making external API requests using cURL.

Uploaded by

agetachew97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Internet Programming II - 2017EC

Chapter 6
APIs & EXTERNAL DATA HANDLING
6.1 Introduction
API (Application Programming Interface) is a set of rules and protocols that allows different software
applications to communicate with each other. APIs define how requests and responses should be
structured so that one system can interact with another seamlessly.

APIs offer several key features that make them essential in software development. Interoperability
enables different software systems to communicate seamlessly, facilitating integration across various
platforms. Reusability allows developers to leverage existing functionalities, reducing redundancy and
speeding up development. Abstraction hides implementation details, exposing only the necessary
functionalities to users, which simplifies usage and enhances maintainability. Additionally, security plays
a crucial role by controlling access to data and functionalities, ensuring that only authorized users or
systems can interact with sensitive resources.

6.1.1. Types of APIs


APIs come in different forms, depending on how they handle data and communication. Each type has its
own advantages and is suited for different use cases.

1 of 11
Internet Programming II - 2017EC

Representational State Transfer

Representational State Transfer (REST) is one of the most widely used API architectures. It relies on
standard HTTP methods like GET, POST, PUT, and DELETE to perform operations. REST APIs work with data
formats such as JSON or XML and follow a stateless approach, meaning each client request must contain
all the necessary information without relying on previous interactions. Popular web services like Twitter
and GitHub use REST APIs for seamless data exchange.

Simple Object Access Protocol

Simple Object Access Protocol (SOAP) is a highly structured API protocol that strictly adheres to predefined
standards. It uses XML for message formatting and supports advanced security features such as WS-
Security, making it a preferred choice for secure transactions. SOAP is commonly used in banking and
financial systems where data integrity and security are critical.

2 of 11
Internet Programming II - 2017EC

GraphQL

GraphQL, developed by Facebook, provides a more flexible approach to data retrieval. Unlike REST, which
returns fixed data structures, GraphQL allows clients to request exactly the data they need. It also uses a
single endpoint instead of multiple endpoints, improving efficiency and reducing over-fetching or under-
fetching of data. Companies like Facebook and GitHub utilize GraphQL APIs to optimize their data queries
and improve performance.

APIs are widely used in modern applications to integrate third-party services and enhance functionality.
For instance, the Google Maps API is essential for location-based services, navigation, and geolocation

tracking, making it a key component in ridesharing apps like for routing and real-time location
updates. Payment gateway APIs such as PayPal, Stripe, and Flutterwave enable secure online transactions
and are commonly used in e-commerce platforms and mobile applications; for example, online stores
integrate the Stripe API to facilitate seamless payment processing. Social media APIs, including those from
Facebook, Twitter, and Instagram, allow applications to interact with social platforms, enabling features
like authentication and content sharing. A common example is the Facebook Login API, which simplifies
user authentication on websites and apps.

6.1.2. RESTful API Principles


REST (Representational State Transfer) is an architectural style for designing networked applications,
which relies on stateless communication between clients and servers. The key principles of RESTful
architecture include statelessness, where each request from a client to a server must contain all the
necessary information to process the request, ensuring that the server does not store any client state
between requests. Another principle is client-server separation, which means the client and server
operate independently, with a clear separation of concerns. REST also emphasizes a uniform interface,
providing a consistent way to interact with resources using standard HTTP methods. In REST, everything
is treated as a resource, which is identified by a unique URL. The layered system principle allows the

3 of 11
Internet Programming II - 2017EC

system to have multiple intermediary layers, such as for security, caching, or load balancing. Lastly,
cacheability is an important feature, where responses must indicate whether they are cacheable to
optimize performance.

HTTP Methods (CRUD Operations)

RESTful APIs use HTTP methods to perform operations on resources, following the CRUD (Create, Read,
Update, Delete) operations. Below is a table showing the HTTP methods used in RESTful APIs and their
corresponding CRUD operations:

HTTP
Operation Description Example
Method
GET Retrieve Fetches data from the server. GET /users → Fetch all users.
(Read) GET /users/1 → Fetch user with ID 1.
POST Create Creates a new resource on the POST /users with JSON body → Creates a
(Create) server. new user.
PUT Update Updates an existing resource on PUT /users/1 with updated data →
(Update) the server. Updates user with ID 1.
DELETE Delete Removes a resource from the DELETE /users/1 → Deletes user with ID
(Delete) server. 1.

Status Codes

HTTP status codes indicate the result of a client’s request. Some commonly used status codes in RESTful
APIs include:

Status Code Description


200 OK – The request was successful.
201 Created – The request was successful and a new resource was created.
204 No Content – The request was successful but there's no content to return.
301 Moved Permanently – The resource has permanently moved to a new URL.
302 Found – Temporary redirect to a different URL.
304 Not Modified – The resource hasn’t changed since the last request.
400 Bad Request – The request is malformed or invalid.
401 Unauthorized – Authentication is required or has failed.
403 Forbidden – Access is not allowed, even with authentication.
404 Not Found – The requested resource could not be found.
405 Method Not Allowed – The request method is not supported.
500 Internal Server Error – A general server error occurred.

4 of 11
Internet Programming II - 2017EC

Status Code Description


502 Bad Gateway – Invalid response from an upstream server.
503 Service Unavailable – The server is temporarily unable to handle the request.
504 Gateway Timeout – The server did not receive a timely response.

Data Formats: JSON vs. XML

RESTful APIs primarily use structured data formats for request and response bodies.

JSON (JavaScript Object Notation) is a lightweight and easy-to-read data format that is widely used in web
and mobile applications. Its simplicity and readability make it a preferred choice for data exchange
between a client and server, especially in RESTful APIs. JSON's structure, based on key-value pairs, allows
for easy parsing and processing, making it highly suitable for modern software development.

{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
XML (eXtensible Markup Language) is a more complex and verbose data format compared to JSON. It is
often used in older systems and enterprise applications where a higher level of structure and flexibility is
required. XML provides a way to define custom tags, which makes it suitable for scenarios where data
needs to be highly structured or when integrating with legacy systems. However, its verbosity and
complexity have made it less favored in modern web and mobile applications.

<user>
<id>1</id>
<name>John Doe</name>
<email>[email protected]</email>
</user>

6.2 Building & Consuming APIs in PHP


6.2.1. Handling Requests & Sending JSON Responses
Building a RESTful API in PHP involves handling client requests and sending appropriate JSON responses.
PHP provides built-in functionalities to work with HTTP requests and responses efficiently.

Receiving Requests

5 of 11
Internet Programming II - 2017EC

PHP APIs handle HTTP requests using $_GET, $_POST, $_REQUEST, or by reading the request body.

Handling a GET request

if ($_SERVER['REQUEST_METHOD'] === 'GET') {


$id = isset($_GET['id']) ? intval($_GET['id']) : null;
echo json_encode(["message" => "Received GET request", "id" => $id]);
}
Handling a POST request

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


$data = json_decode(file_get_contents("php://input"), true);
echo json_encode(["message" => "Received POST request", "data" =>
$data]);
}
Handling Other HTTP Methods

switch ($_SERVER['REQUEST_METHOD']) {
case 'PUT':
parse_str(file_get_contents("php://input"), $putData);
echo json_encode(["message" => "Received PUT request", "data" =>
$putData]);
break;
case 'DELETE':
echo json_encode(["message" => "Received DELETE request"]);
break;
default:
echo json_encode(["message" => "Unsupported request method"]);
}
Sending JSON Responses

To return JSON responses, follow these guidelines. Set the appropriate Content-Type header to indicate
that the response is in JSON format. Use json_encode() to convert PHP arrays or objects into JSON.
Additionally, set response codes using http_response_code() to ensure proper status indication.

Sending a JSON response

header("Content-Type: application/json");
http_response_code(200);
$response = [
"status" => "success",

6 of 11
Internet Programming II - 2017EC

"message" => "Data retrieved successfully",


"data" => ["id" => 1, "name" => "Sample"]
];
echo json_encode($response);
Sending Error Responses

function sendErrorResponse($message, $code = 400) {


http_response_code($code);
echo json_encode(["status" => "error", "message" => $message]);
exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {


sendErrorResponse("Only GET requests are allowed", 405);
}

6.2.2. Making External API Requests in PHP


Making API requests in PHP allows communication with external services over HTTP. PHP provides
different methods to perform API requests, such as file_get_contents() for simple requests and
cURL for advanced operations.

Using file_get_contents() for Simple Requests

The file_get_contents() function is a straightforward way to make GET requests to an API.

Example

$url = "https://api.example.com/data";
$response = file_get_contents($url);
if ($response === FALSE) {
die("Error occurred while fetching data.");
}
$data = json_decode($response, true);
print_r($data);
The file_get_contents() function has several limitations. It only supports simple GET requests and does
not allow setting headers or handling authentication. Additionally, it offers limited error handling
capabilities.

Using cURL for Advanced Requests

7 of 11
Internet Programming II - 2017EC

cURL provides more flexibility and supports multiple HTTP methods, headers, authentication, and error
handling.

Making a GET Request with cURL

$url = "https://api.example.com/data";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if (curl_errno($ch)) {
die("cURL error: " . curl_error($ch));
}
curl_close($ch);
$data = json_decode($response, true);
print_r($data);
Making a POST Request with cURL

$url = "https://api.example.com/create";
$data = ["name" => "John", "email" => "[email protected]"];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);

if (curl_errno($ch)) {
die("cURL error: " . curl_error($ch));
}
curl_close($ch);
$data = json_decode($response, true);
print_r($data);

Handling API Responses & Errors

Checking HTTP Status Codes

$url = "https://api.example.com/data";

8 of 11
Internet Programming II - 2017EC

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {


die("API request failed with status code: " . $httpCode);
}
Handling Errors in API Requests

$ch = curl_init("https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if ($response === false) {


die("cURL Error: " . curl_error($ch));
}

$data = json_decode($response, true);


if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON decoding error: " . json_last_error_msg());
}
curl_close($ch);
print_r($data);

6.2.3. Fetching & Displaying External API Data


Fetching Data from Public APIs

Public APIs provide useful data (e.g., weather, news, stock prices). Use file_get_contents() or cURL to fetch
data from these APIs.

Example

<?php
$apiKey = "your_api_key";

9 of 11
Internet Programming II - 2017EC

$city = "Addis Ababa";


$url =
"https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKe
y&units=metric";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$weatherData = json_decode($response, true);


echo "Temperature in $city: " . $weatherData["main"]["temp"] . "°C";
?>

Parsing JSON Responses

Use json_decode() to convert JSON responses into PHP arrays or objects.

Example

<?php
$jsonString = '{"name": "John", "age": 30}';
$data = json_decode($jsonString, true);
echo "Name: " . $data["name"];
?>

Displaying API Data in a PHP Application

After parsing the data, dynamically display it in your application.

Example

<?php
$weatherInfo = "Temperature: " . $weatherData["main"]["temp"] . "°C";

//refer back the above example about $weatherData["main"]["temp"]


?>
<div>
<h2>Weather Info</h2>

10 of 11
Internet Programming II - 2017EC

<p><?php echo $weatherInfo; ?></p>


</div>

11 of 11

You might also like