DevToolBox무료
블로그

curl을 코드로: curl 명령을 프로그래밍 언어로 변환

10분 읽기by DevToolBox

Convertir des commandes cURL en code est une tache courante en developpement API. Ce guide montre comment convertir cURL en JavaScript, Python, Go, PHP et Node.js.

Essayez notre convertisseur gratuit cURL vers code.

Comprendre la syntaxe cURL

cURL est un outil en ligne de commande pour le transfert de donnees. C'est le standard pour tester les APIs HTTP.

Une commande cURL consiste en le binaire curl suivi d'une URL et de drapeaux optionnels.

Les drapeaux cURL les plus importants : -X (methode), -H (en-tete), -d (donnees), -u (auth), -F (formulaire).

Reference des drapeaux cURL

Les drapeaux cURL les plus utilises :

DrapeauForme longueUsageExemple
-X--requestMethode HTTP-X POST
-H--headerEn-tete-H "Content-Type: application/json"
-d--dataCorps-d '{"key":"value"}'

cURL vers JavaScript : fetch et axios

API fetch JavaScript

L'API fetch est integree aux navigateurs modernes et Node.js 18+ :

// 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 offre une API plus propre que fetch :

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 vers Python : bibliotheque requests

La bibliotheque requests de Python traduit naturellement les commandes 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/5xx

cURL vers Go : package net/http

Le package standard net/http de Go offre un controle complet :

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 vers PHP : Extension cURL et Guzzle

PHP a une extension cURL integree plus des alternatives comme 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);

Patterns d'appel API courants

La plupart des appels API suivent quelques patterns communs :

GET avec parametres : Le plus simple.

POST avec corps JSON : La mutation API la plus courante.

Authentification Bearer token.

Upload de fichier.

Bonnes pratiques

Toujours definir Content-Type explicitement.

Gerer les erreurs : verifier les codes HTTP.

Variables d'environnement pour les secrets.

Definir des timeouts.

HTTPS en production.

Parser correctement les reponses.

Respecter les limites de debit.

Outils connexes : JSON Formatter, JWT Decoder, URL Encoder.

cURL ConverterJSON FormatterJWT DecoderURL Encoder/Decoder

Questions frequemment posees

Comment convertir cURL en JavaScript fetch ?

Mappez les drapeaux cURL aux options fetch. Notre outil automatise ce processus.

Quelle difference entre -d et -F ?

-d envoie du texte/form-urlencoded, -F envoie du multipart/form-data pour les fichiers.

Comment gerer l'authentification basique en Python ?

Utilisez auth=("user", "password") avec requests.

Peut-on convertir vers plusieurs langages ?

Oui, notre outil genere du code JavaScript, Python, Go, PHP et plus.

Comment convertir un upload de fichier ?

JavaScript: FormData, Python: requests.post(files=...), Go: multipart.NewWriter.

Convertir cURL en code est une competence fondamentale en developpement API.

Convertissez des commandes cURL en code avec notre outil gratuit.

Related Developer Tools and Guides

𝕏 Twitterin LinkedIn
도움이 되었나요?

최신 소식 받기

주간 개발 팁과 새 도구 알림을 받으세요.

스팸 없음. 언제든 구독 해지 가능.

Try These Related Tools

🔄cURL to Code Converterc→JcURL to JavaScript Converter🔗URL Parser{ }JSON Formatter

Related Articles

curl 명령어 치트시트: API 테스트를 위한 50+ 예제

최고의 curl 치트시트. GET, POST, 헤더, 인증, 파일 업로드, 디버깅을 다룹니다.

REST API 모범 사례: 2026년 완전 가이드

REST API 설계 모범 사례: 네이밍 규칙, 에러 처리, 인증, 페이지네이션, 보안을 배웁니다.