Skip to content
Home » Complete Guide to cURL POST Requests: 30+ Examples and Use Cases

Complete Guide to cURL POST Requests: 30+ Examples and Use Cases

  • by

Introduction to cURL POST Requests

cURL (Client for URLs) is one of the most versatile command-line tools for transferring data with servers. When it comes to making POST requests, cURL provides extensive functionality for testing APIs, submitting forms, uploading files, and handling authentication. This comprehensive guide covers everything you need to know about making POST requests with cURL, from basic examples to advanced use cases.

Basic cURL POST Request Syntax

The fundamental syntax for making a POST request with cURL is straightforward:

curl -X POST [options] [URL]

However, there are multiple ways to specify POST requests, and choosing the right approach depends on your specific needs.

Method 1: Using –data Parameter

The most common way to send POST data is using the --data or -d parameter:

# Basic form data
curl --data "param1=value1¶m2=value2" https://httpbin.org/post

# Using -d shorthand
curl -d "param1=value1¶m2=value2" https://httpbin.org/post

Method 2: Using –form for Multipart Data

When uploading files or sending multipart form data, use the --form or -F parameter:

# File upload
curl --form "[email protected]" https://httpbin.org/post

# Multiple form fields with file
curl --form "[email protected]" --form "name=John" --form "[email protected]" https://httpbin.org/post

JSON POST Requests

Modern APIs predominantly use JSON for data exchange. Here’s how to send JSON data with cURL:

Inline JSON Data

# Sending JSON inline
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"[email protected]","age":30}' \
  https://jsonplaceholder.typicode.com/users

JSON from File

# Reading JSON from file
curl -X POST \
  -H "Content-Type: application/json" \
  -d @user.json \
  https://jsonplaceholder.typicode.com/users

Using the –json Flag (cURL 7.82+)

Recent versions of cURL include a convenient --json flag that automatically sets the correct headers:

# Modern JSON syntax
curl --json '{"name":"John","email":"[email protected]"}' https://httpbin.org/post

# Reading from file with --json
curl --json @data.json https://httpbin.org/post

Authentication Methods

Most APIs require authentication. Here are the most common authentication methods with cURL:

Basic Authentication

# Using --user parameter
curl --user "username:password" \
  -X POST \
  -d "data=example" \
  https://api.example.com/endpoint

# Using Authorization header manually
curl -H "Authorization: Basic $(echo -n 'username:password' | base64)" \
  -X POST \
  -d "data=example" \
  https://api.example.com/endpoint

Bearer Token Authentication

# API key authentication
curl -H "Authorization: Bearer YOUR_API_TOKEN" \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"message":"Hello API"}' \
  https://api.example.com/messages

OAuth2 Token

# Using OAuth2 token
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"action":"create","resource":"document"}' \
  https://api.service.com/v1/resources

Advanced POST Request Examples

File Uploads with Progress

# Upload with progress bar
curl --progress-bar \
  -F "[email protected]" \
  -F "description=Important document" \
  https://upload.example.com/files

Multiple Files Upload

# Uploading multiple files
curl -F "[email protected]" \
  -F "[email protected]" \
  -F "metadata={\"category\":\"documents\"};type=application/json" \
  https://api.example.com/upload

Custom Headers

# Adding custom headers
curl -X POST \
  -H "Content-Type: application/json" \
  -H "X-API-Version: v2" \
  -H "X-Request-ID: 12345" \
  -H "Accept: application/json" \
  -d '{"query":"search term"}' \
  https://api.example.com/search

Error Handling and Debugging

Verbose Output for Debugging

# Verbose output to see full request/response
curl -v -X POST \
  -H "Content-Type: application/json" \
  -d '{"test":"data"}' \
  https://httpbin.org/post

# Save headers to file
curl -D headers.txt \
  -X POST \
  -d "param=value" \
  https://httpbin.org/post

Handling Different Response Codes

# Fail on HTTP errors
curl --fail \
  -X POST \
  -d "data=test" \
  https://api.example.com/endpoint

# Get only HTTP status code
curl -o /dev/null -s -w "%{http_code}\n" \
  -X POST \
  -d "test=data" \
  https://httpbin.org/post

Real-World API Examples

GitHub API

# Creating a GitHub repository
curl -X POST \
  -H "Authorization: token YOUR_GITHUB_TOKEN" \
  -H "Accept: application/vnd.github.v3+json" \
  -d '{"name":"my-new-repo","description":"Created via API","private":false}' \
  https://api.github.com/user/repos

Slack Webhook

# Sending message to Slack
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"text":"Hello from cURL!","channel":"#general","username":"bot"}' \
  https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK

Discord Webhook

# Posting to Discord channel
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"content":"Message from cURL","username":"API Bot"}' \
  https://discord.com/api/webhooks/YOUR_WEBHOOK_URL

Performance and Optimization

Connection Reuse

# Using connection reuse for multiple requests
curl -X POST \
  --keepalive-time 60 \
  -H "Connection: keep-alive" \
  -d "data=batch1" \
  https://api.example.com/endpoint

Timeout Settings

# Setting timeouts
curl --connect-timeout 10 \
  --max-time 30 \
  -X POST \
  -d "data=test" \
  https://api.example.com/slow-endpoint

Following Redirects

# Follow redirects automatically
curl -L -X POST \
  -d "follow=redirect" \
  https://example.com/api/endpoint

Security Considerations

SSL/TLS Verification

# Skip SSL verification (NOT recommended for production)
curl -k -X POST \
  -d "data=test" \
  https://self-signed.example.com/api

# Use specific CA certificate
curl --cacert ca-certificate.pem \
  -X POST \
  -d "secure=data" \
  https://secure-api.example.com/endpoint

Using Environment Variables for Sensitive Data

# Store sensitive data in environment variables
export API_TOKEN="your-secret-token"
export API_URL="https://api.example.com"

curl -H "Authorization: Bearer $API_TOKEN" \
  -X POST \
  -d '{"message":"secure"}' \
  "$API_URL/messages"

Common POST Request Patterns

REST API CRUD Operations

# Create a new resource
curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"title":"New Article","content":"Article content","published":true}' \
  https://api.blog.com/articles

# Update existing resource
curl -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"title":"Updated Article","published":false}' \
  https://api.blog.com/articles/123

GraphQL Queries

# GraphQL mutation
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"query":"mutation { createUser(name: \"John\", email: \"[email protected]\") { id name } }"}' \
  https://api.example.com/graphql

Troubleshooting Common Issues

Content-Type Issues

One of the most common issues is incorrect Content-Type headers. Always ensure you’re using the correct Content-Type:

# Wrong - will default to application/x-www-form-urlencoded
curl -X POST -d '{"json":"data"}' https://api.example.com/endpoint

# Correct - explicitly set JSON Content-Type
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"json":"data"}' \
  https://api.example.com/endpoint

Character Encoding

# Handling special characters
curl -X POST \
  -H "Content-Type: application/json; charset=utf-8" \
  -d '{"message":"Hello 世界 🌍"}' \
  https://api.example.com/messages

Large Payload Handling

# For large files, use --data-binary to prevent processing
curl -X POST \
  -H "Content-Type: application/octet-stream" \
  --data-binary @large-file.bin \
  https://upload.example.com/binary

Testing and Validation

Response Validation

# Save response for validation
curl -X POST \
  -d "test=data" \
  -o response.json \
  -w "HTTP Status: %{http_code}\nTotal Time: %{time_total}s\n" \
  https://httpbin.org/post

# Extract specific data from JSON response
curl -s -X POST \
  -H "Content-Type: application/json" \
  -d '{"query":"test"}' \
  https://api.example.com/search | jq '.results[0].id'

Automation and Scripting

Bash Script Example

#!/bin/bash

# Function to make authenticated POST request
make_api_request() {
    local endpoint=$1
    local data=$2
    
    curl -X POST \
        -H "Authorization: Bearer $API_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$data" \
        --fail \
        --silent \
        --show-error \
        "$API_BASE_URL/$endpoint"
}

# Usage
API_TOKEN="your-token"
API_BASE_URL="https://api.example.com"

response=$(make_api_request "users" '{"name":"John","email":"[email protected]"}')
echo "User created: $response"

Modern cURL Features (2024-2025)

HTTP/3 Support

# Using HTTP/3 (if supported)
curl --http3 \
  -X POST \
  -d "modern=protocol" \
  https://http3.example.com/api

Parallel Requests

# Parallel requests with xargs
echo -e "endpoint1\nendpoint2\nendpoint3" | \
xargs -I {} -P 3 curl -X POST \
  -d "data=test" \
  https://api.example.com/{}

Best Practices

When using cURL for POST requests, follow these best practices:

  • Always specify Content-Type: Explicitly set the Content-Type header to avoid ambiguity
  • Use environment variables: Store sensitive data like API keys in environment variables
  • Implement proper error handling: Use --fail flag and check HTTP status codes
  • Enable verbose mode for debugging: Use -v flag when troubleshooting
  • Set appropriate timeouts: Use --connect-timeout and --max-time for reliability
  • Validate SSL certificates: Never use -k flag in production environments
  • Use proper data encoding: Use --data-urlencode for URL encoding when needed

Conclusion

cURL is an incredibly powerful tool for making POST requests, offering flexibility for everything from simple form submissions to complex API interactions. Whether you’re testing APIs during development, automating deployments, or integrating with third-party services, mastering cURL POST requests is essential for any developer or system administrator.

This guide covered the most common use cases and advanced techniques for cURL POST requests. Remember to always consider security, error handling, and proper data formatting when implementing cURL in your workflows. With these examples and best practices, you’ll be well-equipped to handle any POST request scenario that comes your way.

Leave a Reply

Your email address will not be published. Required fields are marked *