Convert Curl to Code: Python, JavaScript, Go, and More
API documentation almost always includes curl examples. Here's how to translate them into actual code for 7 different languages.
Why Convert Curl to Code?
Curl is the universal language of API documentation. When Stripe, GitHub, Twilio, or any other API provider shows you how to use their API, they show you a curl command. It's concise, unambiguous, and works on any system.
But curl commands aren't production code. You can't ship a bash script full of curl calls (well, you shouldn't). You need to translate that curl into whatever language your application is written in. This guide shows you the mapping between curl flags and the equivalent code in Python, JavaScript, Go, Rust, PHP, Java, and Ruby.
Anatomy of a Curl Command
Before converting, let's break down what a curl command contains. Consider this example:
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk_test_abc123" \
-d '{"amount": 2000, "currency": "usd"}' \
https://api.stripe.com/v1/chargesThis command has five distinct pieces: the method (POST), two headers (Content-Type and Authorization), a JSON body, and the URL. Every language's HTTP library has a way to set each of these.
Python (requests)
Python's requests library is the most popular HTTP client in any language. It maps almost 1:1 with curl flags:
import requests
response = requests.post(
"https://api.stripe.com/v1/charges",
headers={
"Content-Type": "application/json",
"Authorization": "Bearer sk_test_abc123",
},
json={"amount": 2000, "currency": "usd"},
)
print(response.status_code)
print(response.json())Key mappings: -X POST becomes requests.post(), -Hbecomes the headers dict, and -d with JSON becomes the json parameter (which also auto-sets Content-Type).
JavaScript (fetch)
The Fetch API is built into every modern browser and Node.js 18+. No external libraries needed:
const response = await fetch("https://api.stripe.com/v1/charges", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer sk_test_abc123",
},
body: JSON.stringify({
amount: 2000,
currency: "usd",
}),
});
const data = await response.json();
console.log(response.status, data);Key difference from curl: in the browser, this request is subject to CORS restrictions. In Node.js, there are no CORS restrictions.
Go (net/http)
Go's standard library handles HTTP without any external dependencies:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"io"
)
func main() {
body, _ := json.Marshal(map[string]interface{}{
"amount": 2000,
"currency": "usd",
})
req, _ := http.NewRequest("POST",
"https://api.stripe.com/v1/charges",
bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer sk_test_abc123")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(respBody))
}Go is more verbose than Python or JavaScript because it uses explicit error handling and requires manual request construction. But this explicitness means fewer surprises in production.
Rust (reqwest)
Rust's reqwest crate is the most popular HTTP client. It's async by default:
use reqwest::Client;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let response = client
.post("https://api.stripe.com/v1/charges")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer sk_test_abc123")
.json(&json!({"amount": 2000, "currency": "usd"}))
.send()
.await?;
println!("{}: {}", response.status(), response.text().await?);
Ok(())
}Curl Flag to Code Mapping
Here's a quick reference for the most common curl flags and their equivalents:
| Curl Flag | What It Does | Code Equivalent |
|---|---|---|
-X METHOD | HTTP method | Method parameter or named function |
-H "Key: Value" | Request header | Headers dict/map |
-d 'data' | Request body | Body/data parameter |
-u user:pass | Basic auth | Auth parameter or Authorization header |
-b "cookies" | Send cookies | Cookie header or cookie jar |
-L | Follow redirects | Usually the default behavior |
Automate the Conversion
Manually translating curl to code is educational, but for everyday work, you want it automated. The API Playground lets you paste any curl command and instantly generates code in all 7 languages. It handles edge cases like cookie flags, Basic auth encoding, form data, and multiline commands with backslash continuations.
To decode the JWT tokens that often appear as Bearer tokens in curl commands, use the JWT Decoder.
Further Reading
- Python Requests Documentation
Official documentation for the Python requests library, the most common HTTP client for Python.
- MDN: Fetch API
Complete reference for the browser-native Fetch API used in JavaScript code generation.
- Go net/http Package
Official Go documentation for the standard library HTTP client and server.
- curl Command Line Options
Official guide to curl command-line options and how they map to HTTP semantics.