API•9 min read
cURL to Code: Convert API Requests to Any Language
Learn to convert cURL commands to PHP, Python, JavaScript, and more. Understand cURL syntax and automate API request conversion.
By Andy Pham
cURL to Code: Convert API Requests to Any Language
cURL is the universal tool for testing APIs. Learn to convert cURL commands to production code in any language.
Understanding cURL Syntax
Basic Structure
curl [options] [URL]
# Common options:
# -X, --request HTTP method (GET, POST, PUT, DELETE)
# -H, --header Add header
# -d, --data Request body
# -u, --user Basic auth
# -k, --insecure Skip SSL verification
# -v, --verbose Show details
Example cURL Commands
# GET request with headers
curl -X GET "https://api.example.com/users" -H "Authorization: Bearer token123" -H "Accept: application/json"
# POST with JSON body
curl -X POST "https://api.example.com/users" -H "Content-Type: application/json" -d '{"name": "John", "email": "john@example.com"}'
# POST with form data
curl -X POST "https://api.example.com/upload" -F "file=@document.pdf" -F "name=My Document"
# Basic authentication
curl -u username:password "https://api.example.com/secure"
Converting to PHP
Using cURL Extension
<?php
// Original: curl -X POST "https://api.example.com/users" // -H "Content-Type: application/json" // -d '{"name": "John"}'
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.example.com/users',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'name' => 'John'
]),
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $response;
?>
Using Guzzle
<?php
use GuzzleHttpClient;
$client = new Client();
$response = $client->post('https://api.example.com/users', [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'name' => 'John'
]
]);
echo $response->getBody();
?>
Converting to JavaScript
Using Fetch API
// Original: curl -X POST "https://api.example.com/users" // -H "Authorization: Bearer token123" // -H "Content-Type: application/json" // -d '{"name": "John"}'
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Authorization': 'Bearer token123',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John'
})
});
const data = await response.json();
console.log(data);
Using Axios
const axios = require('axios');
const response = await axios.post('https://api.example.com/users', {
name: 'John'
}, {
headers: {
'Authorization': 'Bearer token123',
'Content-Type': 'application/json'
}
});
console.log(response.data);
Converting to Python
Using Requests
import requests
# Original: curl -X POST "https://api.example.com/users" # -H "Content-Type: application/json" # -d '{"name": "John"}'
response = requests.post(
'https://api.example.com/users',
headers={
'Content-Type': 'application/json',
},
json={
'name': 'John'
}
)
print(response.json())
File Upload
# Original: curl -F "file=@document.pdf" https://api.example.com/upload
with open('document.pdf', 'rb') as f:
response = requests.post(
'https://api.example.com/upload',
files={'file': f}
)
Common cURL Options Mapping
| cURL Option | PHP | JavaScript | Python |
|---|---|---|---|
| -X POST | CURLOPT_CUSTOMREQUEST | method: 'POST' | method='POST' |
| -H "Header: Value" | CURLOPT_HTTPHEADER | headers: {} | headers={} |
| -d "data" | CURLOPT_POSTFIELDS | body: | data= |
| -u user:pass | CURLOPT_USERPWD | Authorization header | auth=() |
| -k | CURLOPT_SSL_VERIFYPEER | agent | verify=False |
Handling Edge Cases
Form Data
// cURL: curl -X POST -d "name=John&email=john@example.com" URL
const formData = new URLSearchParams();
formData.append('name', 'John');
formData.append('email', 'john@example.com');
fetch(url, {
method: 'POST',
body: formData
});
Basic Auth
// cURL: curl -u username:password URL
const credentials = btoa('username:password');
fetch(url, {
headers: {
'Authorization': `Basic ${credentials}`
}
});
Cookies
// cURL: curl -b "session=abc123" URL
fetch(url, {
credentials: 'include',
headers: {
'Cookie': 'session=abc123'
}
});
Automated Conversion
// Simple cURL parser
function parseCurl(curlCommand) {
const result = {
method: 'GET',
url: '',
headers: {},
body: null
};
// Extract URL
const urlMatch = curlCommand.match(/"(https?://[^"]+)"/);
if (urlMatch) result.url = urlMatch[1];
// Extract method
const methodMatch = curlCommand.match(/-Xs+(w+)/);
if (methodMatch) result.method = methodMatch[1];
// Extract headers
const headerMatches = curlCommand.matchAll(/-Hs+"([^:]+):s*([^"]+)"/g);
for (const match of headerMatches) {
result.headers[match[1]] = match[2];
}
// Extract data
const dataMatch = curlCommand.match(/-ds+'([^']+)'/);
if (dataMatch) result.body = dataMatch[1];
return result;
}
Try Our Tools
- cURL to PHP - Convert cURL to PHP code
Conclusion
Converting cURL commands to code is essential for API development. Understanding the mapping between cURL options and language-specific HTTP clients makes this process straightforward.