PHPSnippet
Last updated at 2023-08-29

Easy PHP REST API Calls using cURL

ClickUp
Note
AI Status
Last Edit By
Last edited time
Aug 29, 2023 05:19 PM
Metatag
Slug
rest-api-using-curl-in-php
Writer
Published
Published
Date
Aug 29, 2023
Category
PHP
Snippet
Making REST API calls in PHP is a common task when you need to interact with third-party APIs. The cURL library provides a powerful way to send HTTP requests and handle responses in your PHP code. It supports various HTTP methods and offers features that simplify networking operations.
In this article, you will learn how to use the cURL library in a PHP project to make REST API calls.

Setting Up a PHP Project

If you're an experienced developer seeking quick reference, you can directly jump to each HTTP endpoint section.
If you're starting a new PHP project, follow these step-by-step instructions to set it up.

Create a Directory for the Project

It's a good practice to create a dedicated directory for your PHP project.
😀
While this is a simple tutorial, you may want to create a big project later. A big project starts small. Over time, as you add version control and keep adding something to it, it becomes a huge project. A profitable project.
To create a directory, use your terminal:
mkdir php_project cd php_project
This will create a directory named php_project and change your terminal's working directory to it.

Create a PHP Script File

Within the php_project directory, create a PHP script file named main.php:
touch main.php
Now you can add a basic script to your main.php file and run it to check if your project is set up properly:
<?php echo "Hello, World!"; ?>
Then run the PHP script:
php main.php

Using cURL Library in PHP

Follow the steps below to utilize the cURL library in your PHP code.

Making a GET Request using cURL

To make a GET request using cURL, you can use the following code snippet:
<?php $baseUrl = "https://jsonplaceholder.typicode.com"; $endpoint = "/posts/1"; $ch = curl_init($baseUrl . $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if ($response === false) { echo "GET Request Failed: " . curl_error($ch); } else { $data = json_decode($response, true); echo "GET Response: "; print_r($data); } curl_close($ch); ?>
In the above example, you use curl_init to initialize a cURL session and set the URL to the desired endpoint. You then set the CURLOPT_RETURNTRANSFER option to ensure cURL returns the response instead of outputting it directly. After executing the request, you handle any errors and decode the JSON response.

Making a POST Request using cURL

To make a POST request using cURL, you can use the following code snippet:
<?php $baseUrl = "https://jsonplaceholder.typicode.com"; $endpoint = "/posts"; $dataToPost = [ "title" => "New Post", "body" => "This is the body of the new post", "userId" => 1 ]; $ch = curl_init($baseUrl . $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dataToPost)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ]); $response = curl_exec($ch); if ($response === false) { echo "POST Request Failed: " . curl_error($ch); } else { $data = json_decode($response, true); echo "POST Response: "; print_r($data); } curl_close($ch); ?>
In this example, you use the curl_setopt function to set various cURL options, such as enabling POST, setting the request payload, and specifying the content type.

Making a PATCH Request using cURL

A PATCH request is used to make partial updates to an existing resource on the server.
phpCopy code <?php $baseUrl = "https://jsonplaceholder.typicode.com"; $endpoint = "/posts/1"; $dataToUpdate = [ "title" => "Updated Post Title" ]; $ch = curl_init($baseUrl . $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dataToUpdate)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ]); $response = curl_exec($ch); if ($response === false) { echo "PATCH Request Failed: " . curl_error($ch); } else { $data = json_decode($response, true); echo "PATCH Response: "; print_r($data); } curl_close($ch); ?>
In this example, you use the CURLOPT_CUSTOMREQUEST option to specify the PATCH method. Similar to the POST example, you provide the request payload and set the appropriate content type.

Making a DELETE Request using cURL

A DELETE request is used to remove a resource from the server.
phpCopy code <?php $baseUrl = "https://jsonplaceholder.typicode.com"; $endpoint = "/posts/1"; $ch = curl_init($baseUrl . $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); $response = curl_exec($ch); if ($response === false) { echo "DELETE Request Failed: " . curl_error($ch); } else { echo "DELETE Request Successful"; } curl_close($ch); ?>
For a DELETE request, you again use the CURLOPT_CUSTOMREQUEST option to specify the DELETE method. Since DELETE requests typically do not require a request payload, you can omit the CURLOPT_POSTFIELDS option.

Wrap Up

That's it! You've learned how to make REST API calls using the cURL library in PHP. With cURL, you can easily handle networking tasks and communicate with remote APIs using various HTTP methods.
For more advanced scenarios and error handling, consider exploring the official PHP documentation and additional resources on cURL and networking in PHP.
 

Discussion (0)

Related Posts