Complete Guide to Using cURL for API Requests

Master cURL for API testing and development. Learn HTTP methods, authentication, data handling, and advanced techniques with practical examples.

Complete Guide to Using cURL for API Requests

Table of Contents

1. [Introduction to cURL](#introduction-to-curl) 2. [Installation and Setup](#installation-and-setup) 3. [Basic cURL Syntax](#basic-curl-syntax) 4. [HTTP Methods with cURL](#http-methods-with-curl) 5. [Headers and Authentication](#headers-and-authentication) 6. [Request Body and Data Handling](#request-body-and-data-handling) 7. [Response Handling](#response-handling) 8. [Advanced cURL Options](#advanced-curl-options) 9. [Common API Patterns](#common-api-patterns) 10. [Error Handling and Debugging](#error-handling-and-debugging) 11. [Best Practices](#best-practices) 12. [Real-World Examples](#real-world-examples)

Introduction to cURL

cURL (Client URL) is a command-line tool and library for transferring data with URLs. It supports numerous protocols including HTTP, HTTPS, FTP, FTPS, and many others. For API development and testing, cURL is an invaluable tool that allows developers to make HTTP requests directly from the command line without needing specialized software or writing custom code.

Why Use cURL for API Requests

| Advantage | Description | |-----------|-------------| | Simplicity | No need for additional software or GUI applications | | Versatility | Supports all HTTP methods and complex request configurations | | Scriptability | Easy to integrate into shell scripts and automation workflows | | Debugging | Provides detailed information about requests and responses | | Cross-platform | Available on virtually all operating systems | | Lightweight | Minimal resource usage compared to GUI alternatives |

Installation and Setup

Installation by Operating System

| Operating System | Installation Command | Notes | |------------------|---------------------|--------| | Ubuntu/Debian | sudo apt-get install curl | Usually pre-installed | | CentOS/RHEL | sudo yum install curl or sudo dnf install curl | May require EPEL repository | | macOS | brew install curl | Pre-installed, Homebrew for latest version | | Windows | Download from curl.se or use WSL | Available in Windows 10+ by default | | Alpine Linux | apk add curl | Common in Docker containers |

Verification

`bash

Check if cURL is installed and view version

curl --version

Expected output format

curl 7.68.0 (x86_64-pc-linux-gnu) libcurl/7.68.0 Release-Date: 2020-01-08 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp Features: AsynchDNS brotli GSS-API HTTP2 HTTPS-proxy IDN IPv6 Kerberos LDAP libz NTLM NTLM_WB PSL SPNEGO SSL TLS-SRP UnixSockets `

Basic cURL Syntax

Command Structure

`bash curl [options] [URL] `

Essential Options Reference

| Option | Long Form | Description | Example | |--------|-----------|-------------|---------| | -X | --request | Specify HTTP method | -X POST | | -H | --header | Add custom header | -H "Content-Type: application/json" | | -d | --data | Send data in request body | -d '{"key":"value"}' | | -i | --include | Include response headers | -i | | -v | --verbose | Verbose output for debugging | -v | | -o | --output | Write output to file | -o response.json | | -s | --silent | Silent mode (no progress bar) | -s | | -f | --fail | Fail silently on HTTP errors | -f |

Basic Examples

`bash

Simple GET request

curl https://api.example.com/users

GET request with verbose output

curl -v https://api.example.com/users

GET request saving response to file

curl -o users.json https://api.example.com/users

GET request with custom header

curl -H "Accept: application/json" https://api.example.com/users `

HTTP Methods with cURL

GET Requests

GET requests are used to retrieve data from a server. This is the default method for cURL.

`bash

Basic GET request

curl https://jsonplaceholder.typicode.com/posts/1

GET with query parameters

curl "https://jsonplaceholder.typicode.com/posts?userId=1"

GET with multiple query parameters

curl "https://api.example.com/search?q=term&limit=10&offset=0"

GET with custom headers

curl -H "Accept: application/json" \ -H "User-Agent: MyApp/1.0" \ https://api.example.com/data `

POST Requests

POST requests are used to send data to a server to create new resources.

`bash

POST with JSON data

curl -X POST \ -H "Content-Type: application/json" \ -d '{"title":"New Post","body":"This is the content","userId":1}' \ https://jsonplaceholder.typicode.com/posts

POST with form data

curl -X POST \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "name=John&email=john@example.com" \ https://api.example.com/users

POST with data from file

curl -X POST \ -H "Content-Type: application/json" \ -d @data.json \ https://api.example.com/users `

PUT Requests

PUT requests are used to update existing resources or create resources at specific URLs.

`bash

PUT to update a resource

curl -X PUT \ -H "Content-Type: application/json" \ -d '{"id":1,"title":"Updated Post","body":"Updated content","userId":1}' \ https://jsonplaceholder.typicode.com/posts/1

PUT with authentication

curl -X PUT \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-token-here" \ -d '{"name":"Updated Name"}' \ https://api.example.com/users/123 `

PATCH Requests

PATCH requests are used for partial updates to existing resources.

`bash

PATCH for partial update

curl -X PATCH \ -H "Content-Type: application/json" \ -d '{"title":"Partially Updated Title"}' \ https://jsonplaceholder.typicode.com/posts/1

PATCH with JSON Patch format

curl -X PATCH \ -H "Content-Type: application/json-patch+json" \ -d '[{"op":"replace","path":"/title","value":"New Title"}]' \ https://api.example.com/posts/1 `

DELETE Requests

DELETE requests are used to remove resources from the server.

`bash

Simple DELETE request

curl -X DELETE https://jsonplaceholder.typicode.com/posts/1

DELETE with authentication

curl -X DELETE \ -H "Authorization: Bearer your-token-here" \ https://api.example.com/users/123

DELETE with confirmation data

curl -X DELETE \ -H "Content-Type: application/json" \ -d '{"confirm":true}' \ https://api.example.com/users/123 `

Headers and Authentication

Common Headers

| Header | Purpose | Example Value | |--------|---------|---------------| | Content-Type | Specify request body format | application/json | | Accept | Specify desired response format | application/json | | Authorization | Authentication credentials | Bearer token123 | | User-Agent | Identify client application | MyApp/1.0 | | X-API-Key | API key authentication | abc123def456 | | Cache-Control | Cache behavior | no-cache |

Authentication Methods

#### Bearer Token Authentication

`bash

Using Authorization header

curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ https://api.example.com/protected

Using custom token header

curl -H "X-Auth-Token: your-api-token" \ https://api.example.com/data `

#### Basic Authentication

`bash

Using -u flag (recommended)

curl -u username:password https://api.example.com/data

Using Authorization header manually

curl -H "Authorization: Basic $(echo -n 'username:password' | base64)" \ https://api.example.com/data

Basic auth with token (password empty)

curl -u token: https://api.example.com/data `

#### API Key Authentication

`bash

API key in header

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

API key in query parameter

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

Custom API key header

curl -H "X-RapidAPI-Key: your-rapidapi-key" \ -H "X-RapidAPI-Host: api.example.com" \ https://api.example.com/data `

Multiple Headers Example

`bash curl -X POST \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -H "Authorization: Bearer your-token" \ -H "X-Client-Version: 1.0.0" \ -H "X-Request-ID: $(uuidgen)" \ -d '{"data":"value"}' \ https://api.example.com/endpoint `

Request Body and Data Handling

JSON Data

#### Inline JSON

`bash

Simple JSON object

curl -X POST \ -H "Content-Type: application/json" \ -d '{"name":"John","age":30,"city":"New York"}' \ https://api.example.com/users

Complex nested JSON

curl -X POST \ -H "Content-Type: application/json" \ -d '{ "user": { "name": "John Doe", "email": "john@example.com", "preferences": { "theme": "dark", "notifications": true }, "tags": ["developer", "api", "testing"] } }' \ https://api.example.com/users `

#### JSON from File

`bash

Create a JSON file

cat > user_data.json << EOF { "name": "Jane Smith", "email": "jane@example.com", "role": "admin", "permissions": ["read", "write", "delete"] } EOF

Send JSON from file

curl -X POST \ -H "Content-Type: application/json" \ -d @user_data.json \ https://api.example.com/users `

Form Data

#### URL-Encoded Form Data

`bash

Simple form data

curl -X POST \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "name=John&email=john@example.com&age=30" \ https://api.example.com/users

Form data with special characters (URL encoded)

curl -X POST \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "message=Hello%20World%21&category=general" \ https://api.example.com/messages `

#### Multipart Form Data

`bash

Multipart form with text fields

curl -X POST \ -F "name=John Doe" \ -F "email=john@example.com" \ -F "age=30" \ https://api.example.com/users

Multipart form with file upload

curl -X POST \ -F "name=John Doe" \ -F "avatar=@profile_picture.jpg" \ -F "document=@resume.pdf" \ https://api.example.com/users

Multipart with custom content type

curl -X POST \ -F "data=@data.json;type=application/json" \ -F "metadata=@meta.xml;type=application/xml" \ https://api.example.com/upload `

Raw Data and Binary Files

`bash

Send raw text data

curl -X POST \ -H "Content-Type: text/plain" \ --data-raw "This is raw text content" \ https://api.example.com/text

Send binary file

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

Send XML data

curl -X POST \ -H "Content-Type: application/xml" \ -d 'Johnjohn@example.com' \ https://api.example.com/users `

Response Handling

Viewing Response Details

#### Basic Response Information

`bash

Include response headers

curl -i https://api.example.com/users

Show only response headers

curl -I https://api.example.com/users

Verbose output (request and response details)

curl -v https://api.example.com/users

Write response headers to file

curl -D headers.txt https://api.example.com/users `

#### Response Status and Timing

`bash

Show HTTP status code only

curl -s -o /dev/null -w "%{http_code}" https://api.example.com/users

Show detailed timing information

curl -w "Time: %{time_total}s\nStatus: %{http_code}\nSize: %{size_download} bytes\n" \ https://api.example.com/users

Custom format string for multiple metrics

curl -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTotal: %{time_total}s\nStatus: %{http_code}\n" \ https://api.example.com/users `

Output Formatting and Processing

#### Saving Responses

`bash

Save response to file

curl -o response.json https://api.example.com/users

Save with original filename from server

curl -O https://api.example.com/files/document.pdf

Append to existing file

curl https://api.example.com/logs >> application.log

Save response and headers separately

curl -D response_headers.txt -o response_body.json https://api.example.com/users `

#### Processing JSON Responses

`bash

Pretty print JSON using jq

curl -s https://jsonplaceholder.typicode.com/users | jq '.'

Extract specific fields

curl -s https://jsonplaceholder.typicode.com/users | jq '.[0].name'

Filter and transform data

curl -s https://jsonplaceholder.typicode.com/users | jq '.[] | {name: .name, email: .email}'

Count items in array

curl -s https://jsonplaceholder.typicode.com/users | jq 'length' `

Format String Variables

| Variable | Description | Example Output | |----------|-------------|----------------| | %{http_code} | HTTP response code | 200 | | %{time_total} | Total time for transfer | 1.234567 | | %{time_namelookup} | Time for DNS lookup | 0.123456 | | %{time_connect} | Time to establish connection | 0.234567 | | %{size_download} | Bytes downloaded | 1024 | | %{speed_download} | Average download speed | 8192 | | %{url_effective} | Final URL after redirects | https://api.example.com/data |

Advanced cURL Options

Connection and Timeout Settings

`bash

Set connection timeout (10 seconds)

curl --connect-timeout 10 https://api.example.com/users

Set maximum time for entire operation (30 seconds)

curl --max-time 30 https://api.example.com/users

Retry on failure (3 times with 5 second delay)

curl --retry 3 --retry-delay 5 https://api.example.com/users

Follow redirects automatically

curl -L https://api.example.com/redirect-endpoint

Limit number of redirects

curl -L --max-redirs 5 https://api.example.com/redirect-endpoint `

SSL and Security Options

`bash

Ignore SSL certificate errors (not recommended for production)

curl -k https://self-signed.example.com/api

Specify CA certificate bundle

curl --cacert /path/to/ca-bundle.crt https://api.example.com/users

Use client certificate for mutual TLS

curl --cert client.pem --key client-key.pem https://api.example.com/secure

Show SSL certificate information

curl -v --cert-status https://api.example.com/users `

Proxy and Network Configuration

`bash

Use HTTP proxy

curl --proxy http://proxy.company.com:8080 https://api.example.com/users

Use SOCKS proxy

curl --socks5 localhost:1080 https://api.example.com/users

Proxy with authentication

curl --proxy http://username:password@proxy.company.com:8080 https://api.example.com/users

Use specific network interface

curl --interface eth0 https://api.example.com/users

Force IPv4 or IPv6

curl -4 https://api.example.com/users # IPv4 curl -6 https://api.example.com/users # IPv6 `

Cookie Handling

`bash

Save cookies to file

curl -c cookies.txt https://api.example.com/login

Load cookies from file

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

Send specific cookie

curl -b "session_id=abc123; user_pref=dark_mode" https://api.example.com/dashboard

Cookie jar (save and load automatically)

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

Common API Patterns

RESTful API Operations

#### Complete CRUD Example

`bash

CREATE - Add new user

curl -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $API_TOKEN" \ -d '{"name":"John Doe","email":"john@example.com","role":"user"}' \ https://api.example.com/users

READ - Get all users

curl -H "Authorization: Bearer $API_TOKEN" \ https://api.example.com/users

READ - Get specific user

curl -H "Authorization: Bearer $API_TOKEN" \ https://api.example.com/users/123

UPDATE - Update user (full replacement)

curl -X PUT \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $API_TOKEN" \ -d '{"name":"John Smith","email":"john.smith@example.com","role":"admin"}' \ https://api.example.com/users/123

UPDATE - Partial update

curl -X PATCH \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $API_TOKEN" \ -d '{"role":"admin"}' \ https://api.example.com/users/123

DELETE - Remove user

curl -X DELETE \ -H "Authorization: Bearer $API_TOKEN" \ https://api.example.com/users/123 `

Pagination and Filtering

`bash

Pagination with limit and offset

curl "https://api.example.com/users?limit=20&offset=40"

Pagination with page numbers

curl "https://api.example.com/users?page=3&per_page=10"

Filtering and sorting

curl "https://api.example.com/users?role=admin&sort=created_at&order=desc"

Search with multiple parameters

curl "https://api.example.com/products?category=electronics&price_min=100&price_max=500&in_stock=true"

Complex filtering with URL encoding

curl "https://api.example.com/search?q=laptop%20gaming&category=computers&brand[]=dell&brand[]=hp" `

File Upload Patterns

`bash

Single file upload

curl -X POST \ -H "Authorization: Bearer $API_TOKEN" \ -F "file=@document.pdf" \ -F "title=Important Document" \ -F "category=legal" \ https://api.example.com/files

Multiple file upload

curl -X POST \ -H "Authorization: Bearer $API_TOKEN" \ -F "files[]=@image1.jpg" \ -F "files[]=@image2.jpg" \ -F "files[]=@image3.jpg" \ -F "album_name=Vacation Photos" \ https://api.example.com/albums

Upload with progress bar

curl -X POST \ -H "Authorization: Bearer $API_TOKEN" \ -F "file=@large_video.mp4" \ --progress-bar \ https://api.example.com/media `

Webhook Testing

`bash

Test webhook endpoint

curl -X POST \ -H "Content-Type: application/json" \ -H "X-Webhook-Signature: sha256=signature_here" \ -d '{ "event": "user.created", "timestamp": "2023-12-01T10:00:00Z", "data": { "user_id": 123, "email": "new.user@example.com" } }' \ https://your-app.com/webhooks/user-events

Simulate different webhook events

curl -X POST \ -H "Content-Type: application/json" \ -d '{"event":"payment.completed","order_id":"12345","amount":99.99}' \ https://your-app.com/webhooks/payments `

Error Handling and Debugging

HTTP Status Code Handling

`bash

Exit with error on HTTP error status

curl -f https://api.example.com/users/999

Show only HTTP status code

curl -s -o /dev/null -w "%{http_code}" https://api.example.com/users

Conditional processing based on status code

STATUS=$(curl -s -o response.json -w "%{http_code}" https://api.example.com/users) if [ $STATUS -eq 200 ]; then echo "Success" cat response.json else echo "Error: HTTP $STATUS" fi `

Common HTTP Status Codes

| Status Code | Meaning | Description | |-------------|---------|-------------| | 200 | OK | Request successful | | 201 | Created | Resource created successfully | | 400 | Bad Request | Invalid request syntax | | 401 | Unauthorized | Authentication required | | 403 | Forbidden | Access denied | | 404 | Not Found | Resource not found | | 422 | Unprocessable Entity | Validation errors | | 429 | Too Many Requests | Rate limit exceeded | | 500 | Internal Server Error | Server error |

Debugging Techniques

`bash

Verbose output for detailed debugging

curl -v https://api.example.com/users

Trace ASCII for even more detail

curl --trace-ascii debug.txt https://api.example.com/users

Show timing breakdown

curl -w "DNS: %{time_namelookup}\nConnect: %{time_connect}\nSSL: %{time_appconnect}\nTransfer: %{time_starttransfer}\nTotal: %{time_total}\n" \ https://api.example.com/users

Test connectivity without transferring data

curl -I --connect-timeout 5 https://api.example.com/health `

Error Response Handling

`bash

Capture both success and error responses

curl -s https://api.example.com/users > response.json 2> error.log

Handle different response types

RESPONSE=$(curl -s https://api.example.com/users) if echo "$RESPONSE" | jq empty 2>/dev/null; then echo "Valid JSON response" echo "$RESPONSE" | jq . else echo "Invalid JSON or error response" echo "$RESPONSE" fi

Retry with exponential backoff

for i in {1..5}; do if curl -f -s https://api.example.com/users; then break else echo "Attempt $i failed, retrying in $((2i)) seconds..." sleep $((2i)) fi done `

Best Practices

Security Best Practices

#### Environment Variables for Sensitive Data

`bash

Store API keys in environment variables

export API_KEY="your-secret-api-key" export API_BASE_URL="https://api.example.com"

Use variables in requests

curl -H "Authorization: Bearer $API_KEY" \ "$API_BASE_URL/users"

Read from secure file

API_KEY=$(cat ~/.config/app/api_key) curl -H "Authorization: Bearer $API_KEY" \ https://api.example.com/users `

#### Avoiding Command Line Exposure

`bash

Bad: API key visible in process list

curl -H "Authorization: Bearer secret-key-123" https://api.example.com/users

Good: Use environment variable

export API_TOKEN="secret-key-123" curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com/users

Good: Read from file

curl -H "Authorization: Bearer $(cat ~/.api_token)" https://api.example.com/users `

Performance Optimization

#### Connection Reuse

`bash

Enable HTTP/2 (if supported by server)

curl --http2 https://api.example.com/users

Keep-alive connections (default in HTTP/1.1)

curl -H "Connection: keep-alive" https://api.example.com/users

Compress response

curl -H "Accept-Encoding: gzip, deflate" https://api.example.com/users `

#### Efficient Data Transfer

`bash

Conditional requests (only if modified)

curl -H "If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT" \ https://api.example.com/users

Request only headers for existence check

curl -I https://api.example.com/users/123

Limit download size

curl --max-filesize 1048576 https://api.example.com/large-data # 1MB limit `

Script Integration

#### Shell Script Example

`bash #!/bin/bash

API configuration

API_BASE="https://api.example.com" API_KEY="${API_KEY:-$(cat ~/.api_key 2>/dev/null)}"

Function to make authenticated requests

api_request() { local method="$1" local endpoint="$2" local data="$3" local curl_opts=(-s -f) curl_opts+=(-H "Authorization: Bearer $API_KEY") curl_opts+=(-H "Content-Type: application/json") if [[ -n "$data" ]]; then curl_opts+=(-d "$data") fi if [[ -n "$method" ]]; then curl_opts+=(-X "$method") fi curl "${curl_opts[@]}" "$API_BASE$endpoint" }

Usage examples

echo "Getting users..." api_request GET "/users" | jq .

echo "Creating user..." api_request POST "/users" '{"name":"Test User","email":"test@example.com"}' | jq .

echo "Updating user..." api_request PATCH "/users/123" '{"name":"Updated Name"}' | jq . `

#### Configuration File Pattern

`bash

config.env

API_BASE_URL=https://api.example.com API_VERSION=v1 TIMEOUT=30 RETRY_COUNT=3

Load configuration

source config.env

Use in requests

curl --max-time "$TIMEOUT" \ --retry "$RETRY_COUNT" \ "$API_BASE_URL/$API_VERSION/users" `

Real-World Examples

GitHub API Integration

`bash

Set GitHub token

GITHUB_TOKEN="your_github_token" GITHUB_API="https://api.github.com"

Get user information

curl -H "Authorization: token $GITHUB_TOKEN" \ "$GITHUB_API/user"

List repositories

curl -H "Authorization: token $GITHUB_TOKEN" \ "$GITHUB_API/user/repos?type=private&sort=updated"

Create a new repository

curl -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "new-repo", "description": "Created via API", "private": true, "auto_init": true }' \ "$GITHUB_API/user/repos"

Create an issue

curl -X POST \ -H "Authorization: token $GITHUB_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "title": "Bug report", "body": "Description of the issue", "labels": ["bug", "priority-high"] }' \ "$GITHUB_API/repos/username/repo/issues" `

Slack API Integration

`bash

Slack webhook URL

SLACK_WEBHOOK="https://hooks.slack.com/services/YOUR/WEBHOOK/URL"

Send simple message

curl -X POST \ -H "Content-Type: application/json" \ -d '{ "text": "Hello from cURL!", "channel": "#general", "username": "curl-bot" }' \ "$SLACK_WEBHOOK"

Send rich message with attachments

curl -X POST \ -H "Content-Type: application/json" \ -d '{ "text": "Deployment Status", "attachments": [ { "color": "good", "title": "Production Deploy", "text": "Version 1.2.3 deployed successfully", "fields": [ { "title": "Environment", "value": "Production", "short": true }, { "title": "Duration", "value": "2m 30s", "short": true } ] } ] }' \ "$SLACK_WEBHOOK" `

E-commerce API Example

`bash

E-commerce API base

STORE_API="https://api.store.com/v1" STORE_TOKEN="your_store_api_token"

Get products with filtering

curl -H "Authorization: Bearer $STORE_TOKEN" \ "$STORE_API/products?category=electronics&in_stock=true&limit=50"

Create new product

curl -X POST \ -H "Authorization: Bearer $STORE_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Wireless Headphones", "description": "High-quality wireless headphones", "price": 99.99, "category": "electronics", "sku": "WH-001", "inventory": 100, "images": [ "https://cdn.store.com/images/wh-001-1.jpg", "https://cdn.store.com/images/wh-001-2.jpg" ], "attributes": { "color": "black", "brand": "TechCorp", "warranty": "2 years" } }' \ "$STORE_API/products"

Process order

curl -X POST \ -H "Authorization: Bearer $STORE_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "customer_id": 12345, "items": [ { "product_id": 67890, "quantity": 2, "price": 99.99 } ], "shipping_address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345", "country": "US" }, "payment_method": "credit_card" }' \ "$STORE_API/orders"

Get order status

curl -H "Authorization: Bearer $STORE_TOKEN" \ "$STORE_API/orders/order-12345/status" `

Weather API Integration

`bash

OpenWeatherMap API example

WEATHER_API_KEY="your_openweather_api_key" WEATHER_API="https://api.openweathermap.org/data/2.5"

Current weather

curl "$WEATHER_API/weather?q=London&appid=$WEATHER_API_KEY&units=metric"

Weather forecast

curl "$WEATHER_API/forecast?q=London&appid=$WEATHER_API_KEY&units=metric&cnt=5"

Weather by coordinates

curl "$WEATHER_API/weather?lat=40.7128&lon=-74.0060&appid=$WEATHER_API_KEY&units=imperial"

Process and format weather data

curl -s "$WEATHER_API/weather?q=London&appid=$WEATHER_API_KEY&units=metric" | \ jq -r '"Current weather in \(.name): \(.weather[0].description), Temperature: \(.main.temp)°C, Humidity: \(.main.humidity)%"' `

Database API Operations

`bash

MongoDB Atlas Data API example

ATLAS_API="https://data.mongodb-api.com/app/your-app-id/endpoint/data/v1" ATLAS_API_KEY="your_atlas_api_key"

Find documents

curl -X POST \ -H "Content-Type: application/json" \ -H "api-key: $ATLAS_API_KEY" \ -d '{ "dataSource": "Cluster0", "database": "sample_db", "collection": "users", "filter": { "status": "active" }, "limit": 10 }' \ "$ATLAS_API/action/find"

Insert document

curl -X POST \ -H "Content-Type: application/json" \ -H "api-key: $ATLAS_API_KEY" \ -d '{ "dataSource": "Cluster0", "database": "sample_db", "collection": "users", "document": { "name": "John Doe", "email": "john@example.com", "created_at": {"$date": "2023-12-01T10:00:00Z"}, "status": "active" } }' \ "$ATLAS_API/action/insertOne"

Update document

curl -X POST \ -H "Content-Type: application/json" \ -H "api-key: $ATLAS_API_KEY" \ -d '{ "dataSource": "Cluster0", "database": "sample_db", "collection": "users", "filter": { "_id": {"$oid": "507f1f77bcf86cd799439011"} }, "update": { "$set": { "last_login": {"$date": "2023-12-01T15:30:00Z"}, "login_count": {"$inc": 1} } } }' \ "$ATLAS_API/action/updateOne" `

This comprehensive guide covers the essential aspects of using cURL for API requests, from basic usage to advanced patterns and real-world examples. The examples and techniques provided should enable you to effectively interact with virtually any REST API using cURL from the command line.

Tags

  • API
  • Command Line
  • HTTP
  • REST
  • curl

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Complete Guide to Using cURL for API Requests