How to Make a cURL API Request in PHP

Learn how to send API requests using cURL in PHP for third-party integrations.

2 min read โ€ข
169 1 0

Learn how to send API requests using PHP's cURL extension , perfect for third-party API integrations.

๐Ÿ“Œ What Is cURL?

cURL is a powerful PHP library that allows you to connect and communicate with external servers through URLs. It supports a variety of protocols including HTTP, HTTPS, FTP, and more , making it a key tool for API integration.

๐Ÿ”Ž Example 1: Basic GET Request

<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ?>

This example fetches data from a public API and outputs the response.

๐Ÿ›ก๏ธ Adding Headers (Authentication)

<?php $ch = curl_init("https://api.example.com/user"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Bearer YOUR_API_KEY", "Accept: application/json" ]); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); print_r($data); ?>

This snippet demonstrates how to include headers for APIs requiring authentication.

๐Ÿ“ค Example 2: POST Request with Data

<?php $data = [ "name" => "John", "email" => "[email protected]" ]; $ch = curl_init("https://api.example.com/submit"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); $response = curl_exec($ch); curl_close($ch); echo $response; ?>

This example sends form data as a POST request to an API endpoint.

๐Ÿงพ Sending JSON Payloads

<?php $data = json_encode([ "username" => "demo", "password" => "secret" ]); $ch = curl_init("https://api.example.com/login"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "Content-Length: " . strlen($data) ]); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); echo $response; ?>

This demonstrates how to send raw JSON using a POST request , a common requirement in modern APIs.

โ— Error Handling

<?php $ch = curl_init("https://api.example.com/test"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { echo "cURL error: " . curl_error($ch); } else { echo $response; } curl_close($ch); ?>

Always check for errors when working with cURL to ensure robustness.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Replying to someone. Cancel