Introduction
cURL is a powerful command-line tool used to transfer data to or from a server. While using APIs, it’s essential to know how to include authentication credentials securely and reliably. In this tutorial, we’ll learn how to send an API key and various authorization credentials using cURL.
Including an API Key in a cURL Request
API keys are often used to identify the calling program to an API. Below is an example of including an API key using the header method:
curl -H "Authorization: Apikey your_api_key" https://api.example.com/data
In some cases, the API key might need to be included as a query parameter:
curl "https://api.example.com/data?apikey=your_api_key"
Basic Authentication Credentials
When an API requires basic authentication, send the username and password using the -u
flag:
curl -u username:password https://api.example.com/data
For increased security, omit the password in the command itself and allow cURL to prompt for it:
curl -u username https://api.example.com/data
cURL will then ask you to enter the password securely, keeping credentials out of the command history.
Bearer Token Authentication
Bearer tokens (often just called ‘tokens’) are the predominant type of access token used with OAuth 2.0. Pass the token in the authorization header using Bearer scheme:
curl -H "Authorization: Bearer your_token" https://api.example.com/data
Digest Authentication
Some APIs use digest authentication. Use cURL’s --digest
flag:
curl --digest -u username:password https://api.example.com/data
Custom Headers
If the API requires a custom header (e.g., a specific API key header or a content-type), use the -H
flag:
curl -H "x-api-key: your_api_key" -H "Content-Type: application/json" https://api.example.com/data
Handling Cookies
APIs might use session cookies to track requests. To store cookies received in the first request and reuse them, save them to a file and use the file in subsequent requests:
curl -c cookies.txt https://api.example.com/data
curl -b cookies.txt https://api.example.com/data2
OAuth 2.0 and cURL
cURL can be used for the entire OAuth 2.0 flow. Here’s how you’d acquire a token:
curl -d "grant_type=client_credentials" -H "Authorization: Basic $(echo -n 'client_id:client_secret' | base64)" https://api.example.com/oauth/token
And then use it:
curl -H "Authorization: Bearer acquired_token" https://api.example.com/data
Conclusion
Using cURL to include authentication credentials like API keys, basic auth credentials, bearer tokens, and custom headers is essential for secure and effective API communication. Understanding the methods and best practices discussed here will help you work more efficiently with APIs.
Keep in mind that security practices change over time. Thus, always check the latest best practices for API credentials handling and use secure ways to store and transmit secrets in your applications.