cURL for API Authentication
How to use cURL with API keys, Bearer tokens, Basic auth, and OAuth 2.0 — with examples.
Published:
Tags: cURL API authentication, curl Bearer token, curl API key header
cURL for API Authentication Authentication is where most API testing with cURL trips developers up — each authentication scheme uses different headers and encoding, and OAuth flows require multiple requests in sequence. This guide covers every auth scheme with exact cURL commands. cURL supports the HTTP authentication options covered here directly; use the API provider's documentation to choose the required scheme. Examples use placeholder hosts and credentials. Copy the header name, token endpoint, scopes, and grant type from the API's current documentation; authentication schemes that look similar are not interchangeable. Start with test credentials that have the minimum permissions required for the request. --- All the tools discussed here are available for free at theproductguy.in —…
Frequently Asked Questions
How do I use an API key with cURL?
Depending on the API, set the key in a header: curl -H 'X-API-Key: your_key' URL, or as Authorization: curl -H 'Authorization: ApiKey your_key' URL, or as a query parameter: curl 'URL?api_key=your_key'. Check the API documentation for the expected format — different APIs use different header names and schemes.
How do I use Bearer tokens with cURL?
Use the -H flag to set the Authorization header with the Bearer scheme: curl -H 'Authorization: Bearer your_access_token' URL. Bearer tokens are used by OAuth 2.0 APIs and JWT-based APIs. The token is typically obtained by first making an authentication request and extracting the access_token from the JSON response.
How do I do Basic auth with cURL?
Use the -u flag: curl -u username:password URL. cURL encodes the credentials as Base64 and sets the Authorization: Basic <encoded> header automatically. For security, omit the password and let cURL prompt you interactively: curl -u username URL. You can also set it manually: curl -H 'Authorization: Basic <base64>' URL.
How do I use OAuth 2.0 with cURL?
For the client credentials flow: POST to the token endpoint with grant_type=client_credentials, client_id, and client_secret, then extract the access_token from the response. For authorization code flow (user context), you need to obtain the authorization code through a browser redirect, then exchange it for tokens via a POST to the token endpoint.
How do I store credentials for cURL?
Store credentials in a .netrc file in your home directory: machine api.example.com login username password secret. cURL reads it automatically with the -n flag: curl -n URL. For API tokens, use shell environment variables: export API_TOKEN=secret, then reference with curl -H 'Authorization: Bearer $API_TOKEN' URL. Never hardcode credentials in scripts.
All articles · theproductguy.in