PHP / PHP APIs and Web Services

Consuming APIs Using cURL

In this tutorial, we will focus on using cURL in PHP to consume APIs. We will make HTTP requests to a REST API and handle the responses.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers creating and consuming REST APIs and working with web services in PHP.

1. Introduction

1.1 Goal of the Tutorial

This tutorial aims to provide a detailed guide on how to consume REST APIs using cURL in PHP. By the end of this tutorial, you will be able to retrieve, create, update, and delete data from an API using HTTP requests.

1.2 Learning Outcomes

  • Understanding what cURL is and how it works
  • Understanding how to use cURL to make GET, POST, PUT, and DELETE requests
  • Knowing how to handle API responses

1.3 Prerequisites

  • Basic knowledge of PHP
  • A working PHP development environment

2. Step-by-Step Guide

cURL is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, etc.). PHP supports libcurl, which adds the ability for PHP to make cURL requests.

2.1 Making a GET Request

Fetch data from an API using a GET request. This is the most common type of HTTP request, used to retrieve data.

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://example.com/api/resource",
  CURLOPT_RETURNTRANSFER => true,
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;

2.2 Making a POST Request

Send data to an API using a POST request. This request is used to create data.

$curl = curl_init();

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://example.com/api/resource",
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_RETURNTRANSFER => true,
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;

3. Code Examples

3.1 GET Request

// Initialize cURL
$curl = curl_init();

// Set cURL options
curl_setopt_array($curl, array(
  CURLOPT_URL => "http://example.com/api/resource",  // API URL
  CURLOPT_RETURNTRANSFER => true,  // Return the result as a string
));

// Execute the cURL session
$response = curl_exec($curl);

// Close the cURL session
curl_close($curl);

// Print the response
echo $response;

3.2 POST Request

// Initialize cURL
$curl = curl_init();

// Data to be sent
$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);

// Set cURL options
curl_setopt_array($curl, array(
  CURLOPT_URL => "http://example.com/api/resource",  // API URL
  CURLOPT_POST => true,  // Set the request method to POST
  CURLOPT_POSTFIELDS => $data,  // Set the POST fields
  CURLOPT_RETURNTRANSFER => true,  // Return the result as a string
));

// Execute the cURL session
$response = curl_exec($curl);

// Close the cURL session
curl_close($curl);

// Print the response
echo $response;

4. Summary

In this tutorial, we've explored how to use cURL in PHP to consume APIs. We learned to make GET and POST requests and handle responses. As next steps, try to make PUT and DELETE requests.

5. Practice Exercises

  1. Make a GET request to any public API and print the response.
  2. Make a POST request to any public API with dummy data and print the response.

Solutions

  1. GET request
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.publicapis.org/entries",
  CURLOPT_RETURNTRANSFER => true,
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;
  1. POST request
$curl = curl_init();

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://dummy.restapiexample.com/api/v1/create",
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_RETURNTRANSFER => true,
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help