How to Remove API Keys Before Sharing a Code Snippet
Learn how to strip API keys from code snippets before sharing them, with a worked fictional example, a redaction checklist, and what to do if a key leaks.
A code snippet is supposed to show how something works, not hand over the keys to your accounts. Yet the snippet you paste into a forum thread, a support ticket, or an AI chat window often carries a live API key in plain sight: in a config dictionary, in an authorization header, or tucked into a URL. Once that text leaves your machine, you cannot control where it goes — search engines index it, chat logs keep copies, and screenshots travel further than the original post.
Removing API keys before you share code is a small habit with an outsized payoff. This guide shows where secrets hide, walks through a full redaction of a fictional example, and explains what to do if a real key has slipped out. Every key below is obviously fake — it contains the word EXAMPLE.
Where secrets hide in a code snippet
Secrets sit in the parts of the code you stop reading because they look like boilerplate.
Config dictionaries and constants
The most common leak is a config block at the top of a file: a dictionary holds the base URL, the key, and the timeout in one tidy place, and the whole block gets copied into the question.
CONFIG = {
"BASE_URL": "https://api.example.com/v1",
"API_KEY": "sk-EXAMPLE-00000000000000000000000000000000",
"TIMEOUT": 30,
}
The key is the problem, but the URL can be one too: a staging hostname tells a reader where your systems live. Replace both with placeholders, or drop the config block and describe the values in words.
Authorization headers
HTTP calls carry credentials in headers, and headers travel with the snippet because they are part of the request. Look for Authorization: Bearer ..., X-Api-Key, and any custom header with a long random value — a bearer token is a password by another name, and anyone holding it can act as you until it expires.
Keys inside URLs
Some services accept a key as a query parameter, and some code builds request URLs by string formatting — leaving a key embedded in a URL that reads like an address:
url = "https://api.example.com/v1/users?api_key=EXAMPLEKEY0000000000000000"
URL-embedded keys are easy to miss because the eye reads the domain and skips the rest. They also leak twice: in the code and in any error message or log line that echoes the full URL. Search for api_key=, token=, and key= anywhere in the snippet.
Environment files, comments, and screenshots
Snippets copied from a terminal often drag their surroundings along: an export API_KEY=... line, a .env file pasted as context, or a curl command with the key inline. A .env file is the worst offender because it exists to hold secrets — pasting it "for context" publishes the entire set at once. Share variable names and structure, never values. The same applies to the material around the code: a comment saying the key is the production one confirms it is real, a stack trace can echo the failed request with its headers, and a screenshot can expose a key in a minimap or a second open tab. Check the whole frame before sharing a screenshot.
Redact a fictional snippet: a worked example
Here is the full routine on one fictional snippet: a small Python script that calls a weather API, with every credential invented and marked EXAMPLE.
Step 1: The snippet as written
import requests
CONFIG = {
"BASE_URL": "https://api.example.com/v1",
"API_KEY": "sk-EXAMPLE-00000000000000000000000000000000",
"TIMEOUT": 30,
}
def get_forecast(city):
headers = {"Authorization": f"Bearer {CONFIG['API_KEY']}"}
response = requests.get(
f"{CONFIG['BASE_URL']}/forecast?city={city}",
headers=headers,
timeout=CONFIG["TIMEOUT"],
)
response.raise_for_status()
return response.json()
print(get_forecast("london"))
The same secret appears twice: in the config dictionary and as a bearer token — so one search-and-replace is not enough.
Step 2: Run it through a pattern redactor
FBSubNet's Sensitive Data Redactor is a useful first pass: paste the snippet in, switch on the categories you need, and it masks likely email addresses, phone-like numbers, and IPv4 addresses with [REDACTED] markers — entirely in your browser, so the text never leaves your device.
But for this snippet, the redactor would change almost nothing: it only looks for email, phone-like, and IPv4 patterns, and an API key matches none of those shapes, so the fake key passes through untouched. The same gap showed up in a companion guide on redacting email addresses in example logs, where the tool caught the addresses and the IP address but missed the key-shaped value. A pattern redactor is a safety net for the things you forgot, not a substitute for reading the snippet yourself.
Step 3: Replace the key by hand
Replace the key with a placeholder that keeps the code readable and makes the redaction obvious, keeping the key name and structure.
import requests
CONFIG = {
"BASE_URL": "https://api.example.com/v1",
"API_KEY": "<YOUR_API_KEY>",
"TIMEOUT": 30,
}
def get_forecast(city):
headers = {"Authorization": "Bearer <YOUR_API_KEY>"}
response = requests.get(
f"{CONFIG['BASE_URL']}/forecast?city={city}",
headers=headers,
timeout=CONFIG["TIMEOUT"],
)
response.raise_for_status()
return response.json()
print(get_forecast("london"))
Both copies changed — the definition and the header — with the same placeholder in both places. The snippet still runs once the reader supplies their own key.
Step 4: Check what the tools missed
Check these before you send the snippet anywhere:
- Search for the key's first characters. If the real key began with
sk-live-, search forsk-. Any hit is a copy you missed. - Search for the field names. Search for
api_key,token,secret, andAuthorization. Every match should show a placeholder, not a value. - Search for long random-looking strings. A run of 20+ letters and digits with no spaces is a key, a token, or a hash — confirm each one is fictional or a placeholder.
A repeatable redaction routine
Redaction works best as a routine you run the same way every time. Five steps, about two minutes.
1. Work on a copy, never the original
Copy the snippet into a scratch file; the original keeps its real key in its proper place. Name the copy clearly, for example snippet.redacted.py, so nobody mistakes it for the working version.
2. Shrink the snippet to the smallest piece that shows the problem
Most questions need ten lines, not a whole file. Cut everything the reader does not need: unrelated functions, unused imports, and configuration for other services. Every line you remove is a line that cannot leak anything.
3. Replace every secret with a descriptive placeholder
Use placeholders that name the kind of value, such as <YOUR_API_KEY>, and keep them consistent: the same key gets the same placeholder everywhere it appears. Avoid empty strings where the value's presence matters — an empty header looks like a bug, while Bearer <YOUR_API_KEY> reads as a deliberate stand-in.
4. Run a pattern check, then a manual check
Paste the redacted copy through the Sensitive Data Redactor to catch the emails, phone numbers, and IP addresses you overlooked, then do the manual search from the checklist above. Neither check is enough alone.
5. Verify the snippet still demonstrates the problem
A redacted snippet that no longer shows the bug is useless. Read it once more and confirm the error and the question are still visible. If removing the key removed context, describe the key's shape in words.
What to do after exposure
Sometimes the check comes too late and the key is already out: posted to a public forum, pasted into an AI chat, or committed to a shared repository. Redacting the copy does not fix the original — treat exposure as a rotation job, not a deletion job.
Revoke or rotate the key first
Go to the service that issued the key and revoke it, then issue a new one — before anything else, including editing the post. Editing a public post does not remove the copies search engines and archives already made. If the service offers rotation, create the new key, update your code, confirm everything works, and only then revoke the old one.
Check what the key could reach
While you rotate, work out what the key could reach: read the service's usage logs since the exposure and look for requests you do not recognise or unexpected charges. If the same key or password was reused anywhere else, rotate those too.
Clean up the copies you control
Once the key is dead, remove the exposed copies you can reach: edit the post, delete the message, and purge the snippet from any ticket. Then deal with version control honestly: removing a key from the latest commit does not remove it from the repository's history, and rewriting history does not recall copies others already cloned. Rotation is the fix. If the key belonged to a team project or a client, tell the team lead or the client plainly what was exposed and what you have done about it.
Common mistakes that leak keys anyway
Most leaks are small assumptions that quietly undo a careful redaction.
- Redacting only part of the key. Showing the first eight characters still gives an attacker a head start, and the prefix alone can identify the account. Replace the whole value.
- Trusting the tool to catch everything. Pattern redactors catch shapes, not secrets: a key in an unusual format or split across lines passes straight through. The manual read is not optional.
- Sharing a screenshot instead of text. A screenshot feels safer because it is an image, but it carries the same text — plus whatever else is on screen: editor tabs and terminal history can expose a key the highlighted lines do not.
- Deleting the message and moving on. Deleting a message removes your copy, not the recipient's copy or the backup. If the key was real, rotate it.
- Using a "fake" key that is actually real. Placeholders copied from documentation or another project can turn out to be live keys. Make example keys obviously fictional — include the word EXAMPLE.
Frequently asked questions
Is it enough to replace the key with asterisks?
For hiding the value, yes; for keeping the snippet useful, a descriptive placeholder is better — ******** says nothing about what belongs there, while <YOUR_API_KEY> is clearer and just as safe.
Can I share the first few characters so support can identify my key?
Only through the service's own support channel, and only if they ask for it. Never put even a prefix in a public post.
Do I need to redact keys in code I share with an AI assistant?
Yes — this is the case people most often skip. An AI chat window is a remote service, not a private notebook, and pasted text may be stored or reviewed. Replace real keys with fictional stand-ins; a short privacy checklist for AI chat prompts covers the same habit.
Conclusion
Removing API keys before sharing a code snippet takes about two minutes: work on a copy, shrink it to the smallest piece that shows the problem, replace every secret with a descriptive placeholder, run a pattern check and a manual check, and confirm the snippet still shows the issue. The pattern check — FBSubNet's Sensitive Data Redactor — catches the emails, phone numbers, and IP addresses you overlook, but it will not catch an API key: a key does not match the shapes it looks for.
And if a key does slip out, remember the order: revoke it first, check what it could reach, clean up the copies you control, and tell the people who need to know. Redaction protects the next snippet; rotation protects the account.