DevToolBoxGRATIS
Blogg

curl Kommandoguide: HTTP-foresporsel, autentisering, filopplasting og kodekonvertering

12 min lesningby DevToolBox

What Is curl?

curl (Client URL) is a command-line tool for transferring data with URLs. It supports HTTP, HTTPS, FTP, SFTP, and many other protocols. curl is pre-installed on macOS, most Linux distributions, and Windows 10+, making it the universal tool for testing APIs, downloading files, and debugging network requests.

Whether you are testing a REST API, downloading files, debugging authentication issues, or automating HTTP requests in scripts, curl is the tool you reach for first. This comprehensive guide covers everything from basic GET requests to advanced features like authentication, file uploads, cookies, and converting curl commands to code.

Convert curl commands to JavaScript, Python, Go, and more with our free tool.

Basic curl Syntax

The basic curl syntax is simple: curl [options] URL. By default, curl makes a GET request and prints the response body to stdout.

# Basic GET request
curl https://api.example.com/users

# Save output to a file
curl -o output.json https://api.example.com/users

# Follow redirects (3xx)
curl -L https://example.com/old-page

# Show response headers along with body
curl -i https://api.example.com/users

# Show only response headers
curl -I https://api.example.com/users

# Silent mode (no progress bar)
curl -s https://api.example.com/users

# Verbose output (for debugging)
curl -v https://api.example.com/users

HTTP Methods: GET, POST, PUT, PATCH, DELETE

curl supports all HTTP methods. Use the -X flag to specify the method (though POST can be inferred from -d).

GET Request

# Simple GET
curl https://api.example.com/users

# GET with query parameters
curl "https://api.example.com/users?page=2&limit=10"

# GET with custom headers
curl -H "Accept: application/json" \
     -H "X-API-Key: your-api-key" \
     https://api.example.com/users

POST Request

# POST with JSON body
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "alice@example.com"}'

# POST with form data (application/x-www-form-urlencoded)
curl -X POST https://api.example.com/login \
  -d "username=alice&password=secret123"

# POST with data from a file
curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d @user.json

# POST with multipart form data (file upload)
curl -X POST https://api.example.com/upload \
  -F "file=@photo.jpg" \
  -F "description=Profile photo"

PUT and PATCH Requests

# PUT - replace entire resource
curl -X PUT https://api.example.com/users/123 \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice Updated", "email": "alice-new@example.com"}'

# PATCH - partial update
curl -X PATCH https://api.example.com/users/123 \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice Updated"}'

DELETE Request

# DELETE
curl -X DELETE https://api.example.com/users/123

# DELETE with authentication
curl -X DELETE https://api.example.com/users/123 \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."

Request Headers

Headers are essential for API communication. Use -H to add custom headers:

# Single header
curl -H "Content-Type: application/json" https://api.example.com/data

# Multiple headers
curl -H "Content-Type: application/json" \
     -H "Authorization: Bearer your-token" \
     -H "Accept: application/json" \
     -H "X-Request-ID: abc-123" \
     https://api.example.com/data

# Common headers reference:
# Content-Type: application/json          (sending JSON)
# Content-Type: multipart/form-data       (file upload)
# Accept: application/json                (expect JSON response)
# Authorization: Bearer <token>           (JWT auth)
# Authorization: Basic <base64>           (Basic auth)
# X-API-Key: <key>                        (API key auth)
# User-Agent: MyApp/1.0                   (custom user agent)
# Cache-Control: no-cache                 (bypass cache)

Authentication Methods

curl supports all common authentication methods:

# ========== Basic Authentication ==========
# Using -u flag (curl encodes to Base64 automatically)
curl -u username:password https://api.example.com/data

# Equivalent manual header
curl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" \
     https://api.example.com/data

# ========== Bearer Token (JWT) ==========
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
     https://api.example.com/data

# ========== API Key ==========
# In header
curl -H "X-API-Key: your-api-key-here" \
     https://api.example.com/data

# In query parameter
curl "https://api.example.com/data?api_key=your-api-key-here"

# ========== OAuth 2.0 Token Request ==========
curl -X POST https://auth.example.com/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=your-client-id" \
  -d "client_secret=your-client-secret"

# ========== Digest Authentication ==========
curl --digest -u username:password https://api.example.com/data

File Upload and Download

# ========== File Upload ==========

# Single file upload
curl -X POST https://api.example.com/upload \
  -F "file=@/path/to/document.pdf"

# Multiple file upload
curl -X POST https://api.example.com/upload \
  -F "files=@photo1.jpg" \
  -F "files=@photo2.jpg" \
  -F "description=Vacation photos"

# Upload with specific content type
curl -X POST https://api.example.com/upload \
  -F "file=@data.csv;type=text/csv"

# Upload raw binary data
curl -X POST https://api.example.com/upload \
  -H "Content-Type: application/octet-stream" \
  --data-binary @image.png

# ========== File Download ==========

# Save with specific filename
curl -o myfile.zip https://example.com/download/file.zip

# Save with server-provided filename
curl -O https://example.com/download/file.zip

# Download with progress bar
curl -# -O https://example.com/large-file.tar.gz

# Resume interrupted download
curl -C - -O https://example.com/large-file.tar.gz

# Download multiple files
curl -O https://example.com/file1.zip -O https://example.com/file2.zip

Working with Cookies

# Send cookies with request
curl -b "session=abc123; theme=dark" https://example.com/dashboard

# Save cookies from response to a file
curl -c cookies.txt https://example.com/login \
  -d "username=alice&password=secret"

# Load cookies from file in subsequent request
curl -b cookies.txt https://example.com/dashboard

# Full session flow: login then access protected page
curl -c cookies.txt -X POST https://example.com/login \
  -d "username=alice&password=secret"

curl -b cookies.txt https://example.com/api/profile

SSL/TLS Options

# Skip SSL certificate verification (development only!)
curl -k https://self-signed.example.com/api

# Specify CA certificate
curl --cacert /path/to/ca-cert.pem https://api.example.com

# Client certificate authentication (mTLS)
curl --cert client-cert.pem \
     --key client-key.pem \
     https://api.example.com

# Show SSL certificate details
curl -vI https://example.com 2>&1 | grep -A 20 "Server certificate"

# Force specific TLS version
curl --tlsv1.3 https://api.example.com

Debugging with curl -v

The -v (verbose) flag is essential for debugging HTTP requests. It shows the complete request/response including headers, TLS handshake, and connection details.

# Verbose output shows everything
curl -v https://api.example.com/users

# Output explanation:
# *  = connection info (DNS, TLS handshake)
# >  = request sent to server (method, headers)
# <  = response from server (status, headers)
# {} = data transferred

# Example verbose output:
# *   Trying 93.184.216.34:443...
# * Connected to api.example.com (93.184.216.34) port 443
# * TLS handshake complete
# > GET /users HTTP/2
# > Host: api.example.com
# > User-Agent: curl/8.4.0
# > Accept: */*
# >
# < HTTP/2 200
# < content-type: application/json
# < content-length: 1234
# <
# [response body]

# Write debug output to file (keep stdout clean)
curl -v https://api.example.com/users 2>debug.log

# Even more detail with --trace
curl --trace trace.log https://api.example.com/users

# Timing information
curl -w "\nDNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTLS: %{time_appconnect}s\nTotal: %{time_total}s\nHTTP Code: %{http_code}\n" \
  -s -o /dev/null https://api.example.com

Timeout and Retry Options

# Connection timeout (seconds)
curl --connect-timeout 5 https://api.example.com

# Maximum time for entire operation
curl --max-time 30 https://api.example.com

# Retry on failure
curl --retry 3 \
     --retry-delay 2 \
     --retry-max-time 60 \
     https://api.example.com/data

# Retry on specific HTTP codes
curl --retry 3 \
     --retry-all-errors \
     https://api.example.com/data

Useful curl One-Liners

# Check if a URL is reachable
curl -Is https://example.com | head -1

# Get your public IP address
curl ifconfig.me
curl ipinfo.io/ip

# Check HTTP response code only
curl -o /dev/null -s -w "%{http_code}\n" https://example.com

# Pretty-print JSON response (with jq)
curl -s https://api.example.com/users | jq .

# Test API latency
curl -s -o /dev/null -w "Total: %{time_total}s\n" https://api.example.com

# Download and extract in one step
curl -sL https://example.com/archive.tar.gz | tar xz

# POST JSON and pretty-print response
curl -s -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "test"}' | jq .

# Parallel requests with xargs
echo "url1 url2 url3" | tr ' ' '\n' | xargs -P 3 -I {} curl -s {}

# Send webhook
curl -X POST https://hooks.slack.com/services/xxx \
  -H "Content-Type: application/json" \
  -d '{"text": "Deployment complete!"}'

Converting curl to Code

After testing an API with curl, you often need to convert the command to your programming language. Here are equivalent examples:

curl to JavaScript (fetch)

// curl command:
// curl -X POST https://api.example.com/users \
//   -H "Content-Type: application/json" \
//   -H "Authorization: Bearer token123" \
//   -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 token123',
  },
  body: JSON.stringify({
    name: 'Alice',
    email: 'alice@example.com',
  }),
});
const data = await response.json();

curl to Python (requests)

# curl command:
# curl -X POST https://api.example.com/users \
#   -H "Content-Type: application/json" \
#   -H "Authorization: Bearer token123" \
#   -d '{"name": "Alice", "email": "alice@example.com"}'

# Python requests equivalent:
import requests

response = requests.post(
    'https://api.example.com/users',
    headers={
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token123',
    },
    json={
        'name': 'Alice',
        'email': 'alice@example.com',
    },
)
data = response.json()

curl to Go

// curl command:
// curl -X POST https://api.example.com/users \
//   -H "Content-Type: application/json" \
//   -d '{"name": "Alice"}'

package main

import (
    "bytes"
    "encoding/json"
    "net/http"
)

func main() {
    body := map[string]string{"name": "Alice"}
    jsonBody, _ := json.Marshal(body)

    req, _ := http.NewRequest("POST",
        "https://api.example.com/users",
        bytes.NewBuffer(jsonBody))

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer token123")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
}

curl Options Quick Reference

curl Options Cheat Sheet:

Request Control:
  -X METHOD          Set HTTP method (GET, POST, PUT, DELETE, PATCH)
  -d DATA            Send data in request body (implies POST)
  -F KEY=VALUE       Multipart form data / file upload
  -H "Key: Value"    Add request header
  -b "cookies"       Send cookies
  -c FILE            Save response cookies to file

Output Control:
  -o FILE            Write output to file
  -O                 Save with original filename
  -s                 Silent mode (no progress)
  -S                 Show errors in silent mode
  -v                 Verbose (show full request/response)
  -i                 Include response headers in output
  -I                 Show response headers only (HEAD request)
  -w FORMAT          Custom output format

Authentication:
  -u USER:PASS       HTTP Basic authentication
  --digest           Use digest authentication
  -E CERT            Client SSL certificate

Connection:
  -L                 Follow redirects
  -k                 Skip SSL verification (insecure!)
  --connect-timeout  Connection timeout (seconds)
  --max-time         Maximum operation time (seconds)
  --retry N          Retry N times on failure
  -x PROXY           Use HTTP proxy
  --http2            Force HTTP/2

Data:
  -d @file           Send file contents as body
  --data-binary @f   Send binary data
  --data-urlencode   URL-encode the data
  -T FILE            Upload file via PUT
  -C -               Resume interrupted transfer

Frequently Asked Questions

What is the difference between curl and wget?

curl and wget are both command-line download tools, but they serve different purposes. curl supports more protocols (not just HTTP), can send data (POST, PUT, etc.), and writes to stdout by default. wget is focused on downloading files, supports recursive downloads, and saves to files by default. For API testing, curl is the standard tool. For mirroring websites or downloading multiple files, wget is often more convenient.

How do I send a curl POST request with JSON?

Use: curl -X POST URL -H "Content-Type: application/json" -d '{"key": "value"}'. The -H flag sets the Content-Type header, and -d provides the JSON body. You can also read the body from a file with -d @file.json.

How do I see the full request and response in curl?

Use the -v flag for verbose output. This shows the complete request (method, headers, body), the TLS handshake, and the full response (status code, headers, body). For even more detail, use --trace filename which shows raw bytes.

How do I handle authentication in curl?

For Basic auth: curl -u username:password URL. For Bearer token: curl -H "Authorization: Bearer TOKEN" URL. For API key: curl -H "X-API-Key: KEY" URL. curl also supports digest, NTLM, and client certificate authentication.

Can I use curl in scripts?

Yes, curl is designed for scripting. Use -s for silent mode, -w for custom output format (e.g., HTTP status code), -o /dev/null to suppress output, and --fail to return a non-zero exit code on HTTP errors. Combine with jq for JSON processing.

Related Tools and Guides

𝕏 Twitterin LinkedIn
Var dette nyttig?

Hold deg oppdatert

Få ukentlige dev-tips og nye verktøy.

Ingen spam. Avslutt når som helst.

Try These Related Tools

c→JcURL to JavaScript Converter{ }JSON Formatter

Related Articles

curl Jukseblad: 50+ Eksempler for API-testing

Det ultimate curl juksebladet.

curl to Code: Convert curl Commands to Any Programming Language

Learn how to convert curl commands to Python, JavaScript, Go, PHP, and more. Practical guide with examples for API integration and code generation.

REST API Best Practices: Den Komplette Guiden for 2026

Lær REST API design best practices: navnkonvensjoner, feilhåndtering, autentisering og sikkerhet.