将 cURL 命令转换为代码是 API 开发中最常见的任务之一。本指南展示如何将 cURL 转换为 JavaScript(fetch 和 axios)、Python(requests)、Go、PHP 和 Node.js,并提供实际 API 调用的示例。
理解 cURL 命令语法
cURL(Client URL)是使用各种网络协议传输数据的命令行工具,是测试 HTTP API 的事实标准。
cURL 命令由 curl 程序、URL 和控制请求方法、头部、正文、认证等的可选标志组成。
API 调用中最重要的 cURL 标志:-X(请求方法)、-H(头部)、-d(数据/正文)、-u(基本认证)、-F(表单数据)、-b(cookies)。
cURL 标志参考
最常用的 cURL 标志及其在代码转换中的含义:
| 标志 | 完整形式 | 用途 | 示例 |
|---|---|---|---|
-X | --request | HTTP 方法 | -X POST |
-H | --header | 请求头 | -H "Content-Type: application/json" |
-d | --data | 请求体 | -d '{"key":"value"}' |
-u | --user | 基本认证 | -u user:password |
-F | --form | 表单数据 | -F "file=@photo.jpg" |
cURL 转 JavaScript:fetch 和 axios
JavaScript fetch API
fetch API 内置于现代浏览器和 Node.js 18+,是 JavaScript 中发起 HTTP 请求的标准方式:
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
// JavaScript fetch equivalent
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_TOKEN",
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com",
}),
});
const data = await response.json();
console.log(data);
// cURL: curl -X GET "https://api.example.com/users?page=1&limit=10" \
// -H "Accept: application/json"
// fetch GET with query parameters
const params = new URLSearchParams({ page: "1", limit: "10" });
const res = await fetch(`https://api.example.com/users?${params}`, {
headers: { Accept: "application/json" },
});
// cURL: curl -u admin:secret123 https://api.example.com/admin
// fetch with Basic Auth
const credentials = btoa("admin:secret123");
const authRes = await fetch("https://api.example.com/admin", {
headers: { Authorization: `Basic ${credentials}` },
});JavaScript axios
axios 是流行的 HTTP 客户端库,提供比 fetch 更简洁的 API:
import axios from "axios";
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
// axios automatically sets Content-Type for objects
const { data } = await axios.post(
"https://api.example.com/users",
{ name: "Alice", email: "alice@example.com" },
{
headers: { Authorization: "Bearer YOUR_TOKEN" },
timeout: 10000, // 10 second timeout
}
);
// cURL: curl -X PUT https://api.example.com/users/123 \
// -H "Content-Type: application/json" \
// -d '{"name":"Alice Updated"}'
const updated = await axios.put(
"https://api.example.com/users/123",
{ name: "Alice Updated" }
);
// cURL: curl -X DELETE https://api.example.com/users/123
await axios.delete("https://api.example.com/users/123");cURL 转 Python:requests 库
Python 的 requests 库是最流行的 HTTP 客户端,cURL 命令可以非常自然地转换:
import requests
# cURL: curl -X POST https://api.example.com/users \
# -H "Content-Type: application/json" \
# -H "Authorization: Bearer YOUR_TOKEN" \
# -d '{"name":"Alice","email":"alice@example.com"}'
response = requests.post(
"https://api.example.com/users",
json={"name": "Alice", "email": "alice@example.com"},
headers={"Authorization": "Bearer YOUR_TOKEN"},
timeout=10,
)
data = response.json()
print(data)
# cURL: curl -u admin:secret123 https://api.example.com/admin
response = requests.get(
"https://api.example.com/admin",
auth=("admin", "secret123"),
)
# cURL: curl -X POST https://api.example.com/upload \
# -F "file=@document.pdf" \
# -F "description=My document"
with open("document.pdf", "rb") as f:
response = requests.post(
"https://api.example.com/upload",
files={"file": ("document.pdf", f, "application/pdf")},
data={"description": "My document"},
)
# cURL: curl -X GET "https://api.example.com/search?q=python&page=1"
response = requests.get(
"https://api.example.com/search",
params={"q": "python", "page": 1},
)
# Error handling
response = requests.post("https://api.example.com/data", json=payload)
response.raise_for_status() # Raises HTTPError for 4xx/5xxcURL 转 Go:net/http 包
Go 标准库的 net/http 包提供 HTTP 请求所需的一切:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
func createUser() error {
payload := map[string]string{
"name": "Alice",
"email": "alice@example.com",
}
body, _ := json.Marshal(payload)
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("POST",
"https://api.example.com/users",
bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer YOUR_TOKEN")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
fmt.Println(string(respBody))
return nil
}cURL 转 PHP:cURL 扩展和 Guzzle
PHP 内置 cURL 扩展,还有现代替代方案 Guzzle:
<?php
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
// PHP cURL extension (built-in)
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.example.com/users",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
"name" => "Alice",
"email" => "alice@example.com"
]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer YOUR_TOKEN"
],
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
print_r($data);
// PHP Guzzle (modern alternative)
// composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$client = new Client(["timeout" => 10]);
$response = $client->post("https://api.example.com/users", [
"json" => ["name" => "Alice", "email" => "alice@example.com"],
"headers" => ["Authorization" => "Bearer YOUR_TOKEN"],
]);
$data = json_decode($response->getBody(), true);常见 API 调用模式
大多数 API 调用属于几种常见模式:
带查询参数的 GET:最简单的模式。
带 JSON 正文的 POST:最常见的 API 变更操作。
Bearer Token 认证:大多数现代 API 使用。
文件上传(multipart/form-data):使用 cURL 的 -F。
cURL 转代码最佳实践
始终显式设置 Content-Type 头。
正确处理错误:检查 HTTP 状态码,实现重试逻辑。
使用环境变量存储密钥:不要硬编码 API 密钥。
设置超时:避免请求挂起。
生产环境使用 HTTPS:不要在生产代码中使用 -k。
正确解析响应体:检查 Content-Type 后再解析。
考虑速率限制:添加请求间延迟,实现指数退避。
相关工具:JSON 格式化器、JWT 解码器、URL 编码/解码器。
cURL ConverterJSON FormatterJWT DecoderURL Encoder/Decoder
常见问题
如何将 cURL 命令转换为 JavaScript fetch?
将 cURL 标志映射到 fetch 选项:-X POST 变为 method: "POST",-H 变为 headers 对象条目,-d 变为 body 参数。我们的免费工具可以自动完成转换。
cURL 中 -d 和 -F 有什么区别?
-d 发送 application/x-www-form-urlencoded 或原始文本数据。-F 发送 multipart/form-data,用于文件上传。
如何在 Python 中处理 cURL 基本认证?
cURL 的 -u user:password 直接映射到 Python requests 的 auth 参数:requests.get(url, auth=("user", "password"))。
可以同时转换为多种编程语言吗?
可以!我们的免费 cURL 转代码转换器解析 cURL 命令并生成 JavaScript、Python、Go、PHP 等语言的等效代码。
如何将带文件上传的 cURL 命令转换为代码?
JavaScript 使用 FormData,Python 使用 requests.post(url, files={...}),Go 使用 multipart.NewWriter。
将 cURL 转换为代码是 API 开发的基础技能。使用我们的免费在线 cURL 转换器自动转换,并遵循本指南的最佳实践。
Related Developer Tools and Guides
- cURL Converter - Convert cURL commands to any programming language
- JSON Formatter - Format and validate JSON API responses
- JWT Decoder - Decode and inspect JWT authentication tokens
- URL Encoder/Decoder - Encode query parameters and URLs
- Base64 Encoder/Decoder - Encode Basic Auth credentials
- JSON to TypeScript - Generate types from API responses
- JSON to Go - Generate Go structs from API responses
- JSON to Python - Generate Python dataclasses from JSON
- HTTP Status Codes - Reference for all HTTP response codes
- cURL Cheat Sheet - Complete cURL command reference
- REST API Best Practices - Design patterns for APIs