Question

Convert a Postman Request to cURL and PHP cURL

phpcurlpostman

Question

I can successfully call my Java web service using Postman with a POST request, and the request inserts records into the database correctly.

I now need to make the same request from PHP using cURL instead of Postman.

Is there a way to export a Postman request as a cURL command, so I can reuse the same method in my PHP code? I have found many examples of converting cURL to Postman, but I need to do the reverse: convert a Postman request to cURL.

For example, if my Postman request includes headers and a request body, I want to produce an equivalent cURL command like this:

curl -X POST "http://example.com/api/items" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -d '{"name":"Book","price":25}'

Then I want to translate that request into PHP cURL code.

Short Answer

By the end of this page, you will understand how a Postman request maps to a cURL command, how to identify the important parts of the request such as method, URL, headers, and body, and how to reproduce the same request in PHP using cURL.

Concept

A Postman request and a cURL request are just two different ways to describe the same HTTP operation.

The core idea is that an HTTP request is made of a few standard parts:

  • HTTP method: GET, POST, PUT, DELETE, etc.
  • URL: the endpoint you are calling
  • Headers: extra metadata such as Content-Type or Authorization
  • Body: the data sent with the request, usually for POST or PUT

Postman provides a graphical interface for building these parts. cURL provides a command-line way to build the same request.

In PHP, the cURL extension lets you create that same HTTP request in code.

This matters because in real applications, developers often test an API in Postman first, then implement the same request in application code. Being able to translate from Postman to cURL or PHP helps you move from manual testing to automation.

A useful way to think about it is:

  • Postman = visual request builder
  • cURL command = text version of the request
  • PHP cURL = programmable version of the request

If you understand the HTTP parts, converting between these tools becomes straightforward.

Mental Model

Think of an HTTP request like sending a package.

  • The URL is the destination address.
  • The method tells what kind of delivery action you want, such as sending new data with POST.
  • The headers are labels on the package, such as Fragile or Express.
  • The body is the actual content inside the package.

Postman is like filling out a form at a shipping desk.

cURL is like writing the shipping instructions in a single command.

PHP cURL is like teaching a program how to prepare and send that package automatically whenever needed.

Take Quiz

Syntax and Examples

Core cURL syntax

curl -X POST "http://example.com/api/items" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -d '{"name":"Book","price":25}'

What each part means

  • -X POST sets the HTTP method
  • "http://example.com/api/items" is the endpoint URL
  • -H adds a request header
  • -d sends the request body

Equivalent PHP cURL example

<?php
$url = "http://example.com/api/items";
$data = json_encode([
    "name" => "Book",
    "price" => 25
]);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer your-token",
    "Content-Length: " . strlen($data)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if ($response === false) {
    echo "cURL error: " . curl_error($ch);
}

curl_close($ch);

echo $response;

Explanation

This PHP code sends the same kind of request as the cURL command:

  • initializes a request to the URL
  • marks it as a POST request
  • sends JSON in the body
  • sets the same headers
  • captures the server response

Important note about Postman

In Postman, you can usually generate code snippets directly from a request, including cURL. That makes it easy to copy the generated command and adapt it to PHP.

Step by Step Execution

Consider this PHP example:

<?php
$url = "http://example.com/api/items";
$data = json_encode(["name" => "Pen"]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

Step by step

  1. json_encode(["name" => "Pen"])

    • Creates the JSON body:
    • {"name":"Pen"}
  2. curl_init($url)

    • Creates a cURL handle for the target URL.
  3. CURLOPT_POST

    • Tells PHP to send a POST request.
  4. CURLOPT_POSTFIELDS

    • Attaches the request body to the POST request.
  5. CURLOPT_HTTPHEADER

    • Adds headers.
    • Here, Content-Type: application/json tells the server the body is JSON.
  6. CURLOPT_RETURNTRANSFER

    • Prevents the response from being printed directly.
    • Instead, the response is stored in $response.
  7. curl_exec($ch)

    • Sends the request to the server.
    • The server processes it and returns a response.
  8. curl_close($ch)

    • Frees the cURL resource.

If the server expects the same headers and body that Postman sends, this PHP code should behave like the Postman request.

Real World Use Cases

This conversion is useful in many real situations:

  • API integration: test an endpoint in Postman, then implement it in PHP
  • Backend automation: replace manual API testing with scheduled scripts
  • Form submission: send user input from a PHP app to another service
  • Microservices: one service calls another service over HTTP
  • Data synchronization: push records from one system into another
  • Webhook simulation: reproduce and debug requests outside Postman

For example, a team might:

  1. build and verify a request in Postman
  2. export it as cURL
  3. turn it into PHP cURL code inside the application
  4. add error handling and logging

That workflow is very common in production development.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just send the request once.

Common patterns include:

Validation before sending

Make sure required values exist before calling the API.

if (empty($token)) {
    throw new Exception("Missing API token");
}

Reusable request wrappers

Instead of repeating cURL setup everywhere, teams often create helper functions.

function postJson($url, array $payload, array $headers = []) {
    $json = json_encode($payload);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([
        "Content-Type: application/json",
        "Content-Length: " . strlen($json)
    ], $headers));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if ($response === false) {
        throw new Exception(curl_error($ch));
    }

    curl_close($ch);
    return $response;
}

Error handling

Developers check both:

  • cURL-level errors, such as connection failures
  • HTTP-level errors, such as 400 or 500
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 400) {
    // log or handle the API error
}

Configuration

URLs, tokens, and credentials are usually stored in config files or environment variables, not hardcoded in source code.

Logging

Teams often log the outgoing request and response when debugging API integrations, while avoiding sensitive data such as passwords or full tokens.

Common Mistakes

1. Forgetting the correct Content-Type

If Postman sends JSON, your PHP code should usually send:

"Content-Type: application/json"

Broken example:

curl_setopt($ch, CURLOPT_POSTFIELDS, ["name" => "Book"]);

Why this is a problem:

  • PHP may send form data instead of JSON.
  • The server may reject the request or parse it incorrectly.

2. Sending an array when the API expects JSON

Correct approach:

$data = json_encode(["name" => "Book"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

3. Missing headers from the Postman request

If your Postman request uses headers such as:

  • Authorization
  • Accept
  • Content-Type
  • custom headers

then your PHP request must include them too.

4. Ignoring cURL errors

Broken example:

$response = curl_exec($ch);
curl_close($ch);

Better:

$response = curl_exec($ch);
if ($response === false) {
    die(curl_error($ch));
}

5. Not checking the HTTP status code

A request can succeed at the network level but still fail at the application level.

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

6. Copying Postman-specific headers blindly

Postman may include headers that are unnecessary or automatically generated. Focus on the headers your API actually requires.

7. Forgetting CURLOPT_RETURNTRANSFER

Without it, the response may be output directly instead of stored in a variable.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Comparisons

Postman vs cURL vs PHP cURL

ToolMain useBest forLimitation
PostmanGUI API testingManual testing and explorationNot application code
cURL commandCommand-line HTTP requestsQuick testing and scriptingLess convenient for large app logic
PHP cURLHTTP requests in PHP codeProduction applications and automationRequires coding and error handling

cURL command vs PHP cURL

AspectcURL commandPHP cURL
FormatShell commandPHP code
Good forQuick terminal testingApplication logic
ReusabilityLimited in app codeEasy to wrap in functions/classes
Error handlingBasic shell outputFull programmatic control

JSON body vs form body

Body typeTypical headerExample
JSONContent-Type: application/json{"name":"Book"}
Form dataContent-Type: application/x-www-form-urlencodedname=Book&price=25

Choosing the correct body format is one of the most important parts of matching the original Postman request.

Take Quiz

Cheat Sheet

Quick mapping from Postman to cURL

  • Method → -X POST
  • URL → request URL
  • Headers → -H "Header-Name: value"
  • Body → -d '...'

Basic cURL command

curl -X POST "http://example.com/api" \
  -H "Content-Type: application/json" \
  -d '{"key":"value"}'

Basic PHP cURL pattern

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

Rules to remember

  • Use json_encode() when sending JSON
  • Match the same headers used in Postman
  • Check curl_error() for transport errors
  • Check CURLINFO_HTTP_CODE for API errors
  • Use CURLOPT_RETURNTRANSFER if you want the response in a variable

Common required headers

  • Content-Type: application/json
  • Authorization: Bearer ...
  • Accept: application/json

Edge cases

  • Some APIs require cookies or custom headers
  • Some APIs expect form data, not JSON
  • Postman may auto-add headers you do not need to copy manually

FAQ

Can Postman export a request as cURL?

Yes. Postman can generate code snippets for requests, including cURL, which you can then adapt into PHP.

Is a Postman request the same as a cURL request?

Yes, if the method, URL, headers, and body are the same, they represent the same HTTP request.

Do I need to copy every header from Postman?

No. Only copy the headers your API actually needs, such as Content-Type, Authorization, and any required custom headers.

Why does my PHP cURL request fail when Postman works?

Usually because of a mismatch in headers, body format, authentication, or missing JSON encoding.

Should I send an array or a JSON string in CURLOPT_POSTFIELDS?

If the API expects JSON, send a JSON string created with json_encode().

How do I see the server response in PHP cURL?

Set CURLOPT_RETURNTRANSFER to true and store the result of curl_exec() in a variable.

How can I debug a PHP cURL request?

Check curl_error($ch), inspect the HTTP status code with curl_getinfo(), and compare the request carefully with the working Postman version.

Take Quiz

Mini Project

Description

Build a small PHP script that sends a POST request to an API endpoint using cURL. This project demonstrates how to take a request you might first test in Postman and implement the same behavior in application code, including headers, JSON body, response handling, and basic error checks.

Goal

Create a reusable PHP script that sends JSON data with a POST request and prints the response and HTTP status code.

Requirements

Requirement 1 Requirement 2 Requirement 3

Take Quiz

Keep learning

Related questions

View more