Sign an API request: Brevily API authentication
Authenticate Brevily API calls with an API key: two headers, or an HMAC-SHA256 signature so the secret never leaves your server. Code for Node and Python.
On this page
Brevily API authentication works with an API key, sent with every call in one of two ways: as two headers carrying the key's ID and secret, or as a signature made with the secret, so the secret itself never leaves your server. Both work on every call. This guide gets you from a new key to a working signed request in Node, Python or the shell, then shows how to check the signed answer and fix a 401.
Before you start: you need an API key and your organisation's code (both below). Keep API errors open for the codes a call can return.
How Brevily API authentication works
Every call goes to the console's address, under /api and your organisation's code:
https://console.brevily.com/api/<ORG>/…Your organisation's code is in Settings › General, under Code, with a copy button. A key only ever answers for its own organisation; another organisation's code returns 404.
You then choose how the key travels:
- Two headers (
x-api-key,x-api-secret): the secret is sent on every call, inside TLS. Suits a server you control, or a quick test. - Signed request (
x-key-id,x-timestamp,x-nonce,x-signature): the secret is never sent. Suits requests that pass through proxies, queues or logs; anywhere a captured request must be useless.
A signed request also can't be replayed: each one carries a nonce the API accepts once.
Organisation key or personal key
- Organisation key: acts for the organisation with the permissions it was given. It keeps working when the person who made it leaves, is suspended or loses a permission, which makes it the right choice for integrations and production systems. To make one, you need permission to manage API keys and access to every folder.
- Personal key: acts as you, within what you can do right now, and stops when you leave the organisation. Good for your own scripts. Make one under Your account › Personal API keys; it asks for your password.
Create an API key and make a first call
- Open Access › API keys and, under Organisation keys, choose New key.
- Give it a Label you'll recognise when you need to revoke it.
- Pick when it Expires: 30, 90, 180 or 365 days, or Never. It's 90 days unless you choose.
- Choose its Permissions. For this guide, Links with View and Create is enough. You can only give a key permissions you hold yourself.
- Enter your Current password and choose Create key.
- Copy the key ID (
brv_ak_…) and the secret. The secret is shown once; if you lose it, roll the key for a new one.
[screenshot: Access › API keys, the New API key dialog with Label, Expires, Permissions and Current password]
Keys are made, rolled and revoked in the console only. No API key can call those pages, so a leaked key can't mint more.
Send your API key in two headers
The quickest way to a first call. Keep the values in shell variables so every command stays short:
API=https://console.brevily.com/apiORG=EXAMPLE # your organisation's codeKEY=brv_ak_… # the key's IDSECRET=… # its secretcurl "$API/$ORG/links?limit=10" \ -H "x-api-key: $KEY" \ -H "x-api-secret: $SECRET"A 200 with a list of links means the key works. From here, signing is a change of headers, nothing else.
How to sign an API request
A signed request sends four headers in place of the two:
x-key-id: the key's ID.x-timestamp: now, in whole Unix seconds.x-nonce: a value of your own, new for every request, 1 to 128 characters. A UUID is ideal.x-signature: HMAC-SHA256 under the secret, in lowercase hex, of the five lines below.
The lines, joined by a newline (\n), with no newline at the end:
- The method in capitals:
GET. - The path as sent, with
/apiand the query string:/api/EXAMPLE/links?limit=10. - The same value as
x-timestamp. - The same value as
x-nonce. sha-256=:<base64>:, the SHA-256 of the exact body bytes in base64. AGEThas an empty body, and that has a digest too.
What the signed string looks like
Here are the five lines for a GET, with made-up values:
GET/api/NORTHWIND/links?limit=1017908464074c3e1f0a-8a5d-4f8e-9b7c-2d6e5a1b0c93sha-256=:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=:Under the made-up secret brv_made_up_secret_for_this_page, they sign to:
2dc6b2c8eb57de99849f2b64aed963a9f5c9fa402e12bb89fa04ed391471042eFeed the same lines and secret to your own code. If it prints that signature, your signer is right, and any 401 from here on is about what you sent, not how you signed it.
Request signing code for Node, Python and the shell
Each function below takes the method, the path exactly as you'll send it, and the exact body, and returns the four headers. Call it for every request, retries included.
Node
import { createHash, createHmac, randomUUID } from 'node:crypto';// path: as sent, with /api and the query; body: the exact text sent.function sign(keyId, secret, method, path, body = '') { const t = String(Math.floor(Date.now() / 1000)); const nonce = randomUUID(); const digest = 'sha-256=:' + createHash('sha256').update(body).digest('base64') + ':'; const signature = createHmac('sha256', secret) .update([method, path, t, nonce, digest].join('\n')) .digest('hex'); return { 'x-key-id': keyId, 'x-timestamp': t, 'x-nonce': nonce, 'x-signature': signature, };}Creating a link with it. Note that the body is turned into text once, and that exact text is both signed and sent:
const { KEY, SECRET, ORG } = process.env;const path = `/api/${ORG}/links`;const body = JSON.stringify({ url: 'https://example.com/spring-sale' });const res = await fetch(`https://console.brevily.com${path}`, { method: 'POST', headers: { ...sign(KEY, SECRET, 'POST', path, body), 'content-type': 'application/json', }, body,});console.log(res.status, await res.json());A 201 comes back with the new link, including its shortUrl and destination.
Python
import base64, hashlib, hmac, time, uuiddef sign(key_id, secret, method, path, body=b""): """path: as sent, with /api and the query. body: the exact bytes sent.""" t = str(int(time.time())) nonce = str(uuid.uuid4()) digest = "sha-256=:" + base64.b64encode(hashlib.sha256(body).digest()).decode() + ":" message = "\n".join([method, path, t, nonce, digest]) signature = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest() return {"x-key-id": key_id, "x-timestamp": t, "x-nonce": nonce, "x-signature": signature}Pass the same bytes you sign as the request body, for example json.dumps(payload).encode(), rather than letting your HTTP library serialise the payload again.
The shell
For a quick test with curl and openssl, using the variables from earlier:
method=GET path="/api/$ORG/links?limit=10" body=''t=$(date +%s)nonce=$(uuidgen | tr 'A-Z' 'a-z')digest="sha-256=:$(printf '%s' "$body" | openssl dgst -sha256 -binary | base64):"signature=$(printf '%s\n%s\n%s\n%s\n%s' "$method" "$path" "$t" "$nonce" "$digest" \ | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')curl -X "$method" "https://console.brevily.com$path" \ -H "x-key-id: $KEY" -H "x-timestamp: $t" \ -H "x-nonce: $nonce" -H "x-signature: $signature"Verify the signed response
The answer to a signed request comes back signed too, so you can tell it really came from Brevily and answers your request rather than someone else's. It carries x-timestamp, x-signature and your nonce, echoed in x-nonce. The signature covers four lines: the status, that timestamp, your nonce and the body's digest.
// nonce: the one you sent; text: the answer's body, read as text.function verify(secret, res, text, nonce) { const digest = 'sha-256=:' + createHash('sha256').update(text).digest('base64') + ':'; const expected = createHmac('sha256', secret) .update([res.status, res.headers.get('x-timestamp'), nonce, digest].join('\n')) .digest('hex'); return res.headers.get('x-nonce') === nonce && res.headers.get('x-signature') === expected;}Read the body as text first, check it, then parse the JSON.
Retrying a signed request
A retry is a new request: sign it again, with a new timestamp and a new nonce. Sending the same signed headers twice is refused, which is exactly what stops a captured request from being replayed.
For writes, add an Idempotency-Key header with a value of your own, the same on every attempt. If the first attempt went through but the answer was lost, the retry returns the first answer and changes nothing, so a link is never created twice. More in the reference's retrying safely.
Troubleshooting a 401 from the Brevily API
Every authentication failure is a 401 with the code UNAUTHENTICATED. When a signed request's timing or nonce is at fault, details.reason says which:
STALE_TIMESTAMP: the timestamp is more than 300 seconds from the server's clock. Sign just before sending, and keep your server's clock set by NTP.INVALID_NONCE: nox-nonce, or one longer than 128 characters. Send a fresh UUID on every request.NONCE_REUSED: the key already used this nonce within the window. Sign every attempt again, retries included.
A 401 with no reason, saying "invalid credential", means the signature doesn't match what arrived. The usual causes:
- The path was signed without
/api, or without its query string. - The body was signed as one string and sent as another, for example re-serialised by an HTTP library.
- The secret has a stray space or newline from copying.
- The key has expired, been revoked, or been rolled more than an hour ago.
A 401 also comes back for a console session or a Bearer token, and for Authorization: ApiKey …. The API only takes the headers on this page.
A 403 ACCESS_DENIED is different: the key is fine, but it lacks the permission the call needs, or your plan doesn't include the feature.
Common questions
Do I have to sign Brevily API requests?
No. The two headers, x-api-key and x-api-secret, work on every call. Sign when the secret mustn't travel, or when requests pass through systems you don't fully trust.
Can I sign Brevily API requests with an RFC 9421 library?
No. Brevily's signed lines borrow RFC 9421's component names, but not its wire format, so a standard RFC 9421 client won't produce a signature Brevily accepts. The functions in this guide are all you need.
Can I call the Brevily API from a browser or a mobile app?
Not with an API key: anyone can read a secret shipped in a web page or an app. Call the API from your server, and keep the secret in its environment or a secrets manager, never in source control. A page or an app that only reports events uses its own website key or app key instead.
What happens to the old Brevily API key when I roll it?
Rolling gives a new key ID and secret with the same permissions and expiry. The old one keeps working for an hour, so you can switch your systems over, then stops. Revoking stops a key at once.
Next steps
- Brevily API: what the API covers, and what each permission allows.
- API errors: every error code, and what to do about it.
- MCP server: create and manage links from AI tools.
- Click webhooks: receive link events as they happen, signed by Brevily for you to check.
On this page