id int64 1 132 | language stringclasses 6
values | library stringclasses 17
values | error_type stringlengths 9 25 | error_message stringlengths 16 93 | broken_code stringlengths 24 383 | explanation stringlengths 55 112 | fixed_code stringlengths 38 455 | key_insight stringlengths 65 109 | tags stringlengths 12 45 |
|---|---|---|---|---|---|---|---|---|---|
1 | rest | generic | content_negotiation | 406 Not Acceptable | GET /api/data
Accept: text/html | The server only produces JSON; sending Accept: text/html returns 406. | GET /api/data
Accept: application/json | Match the Accept header to the media types the server advertises. | rest,content-negotiation,406 |
2 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.slack.com/api/chat.postMessage") | No timeout set on call to slack endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.slack.com/api/chat.postMessage", timeout=5)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,slack |
3 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.slack.com/api/chat.postMessage") | No timeout set on call to slack endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.slack.com/api/chat.postMessage", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,slack |
4 | javascript | axios | cancel_request | CanceledError unhandled when navigating away | const source = axios.CancelToken.source();
axios.get("/slow-api", { cancelToken: source.token });
source.cancel(); | Cancellation throws a CanceledError that must be caught and handled. | const controller = new AbortController();
try {
const resp = await axios.get("/slow-api", { signal: controller.signal });
process(resp.data);
} catch (err) {
if (!axios.isCancel(err)) throw err;
}
// to cancel: controller.abort(); | Use AbortController with axios (v1+) and filter cancellations with axios.isCancel(err). | axios,cancel,abort |
5 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | The mapbox API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,mapbox |
6 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | The msgraph API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,msgraph |
7 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues") | No timeout set on call to github endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues", timeout=60)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,github |
8 | python | requests | stream_large_response | MemoryError downloading large file | resp = requests.get("https://example.com/large-file.zip")
with open("large-file.zip", "wb") as f:
f.write(resp.content) | resp.content loads the entire response into memory. For large files, stream the response. | resp = requests.get("https://example.com/large-file.zip", stream=True)
with open("large-file.zip", "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk) | Use stream=True and iter_content() to download large files without loading them into memory. | streaming,download,memory |
9 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.slack.com/api/chat.postMessage") | The slack API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://api.slack.com/api/chat.postMessage", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,slack |
10 | python | stripe | expand_nested | AttributeError: PaymentIntent has no attribute 'customer' — got string ID | intent = stripe.PaymentIntent.retrieve("pi_...")
print(intent.customer.email) # intent.customer is a string ID | By default Stripe returns nested object IDs as strings. Use expand= to include full objects. | intent = stripe.PaymentIntent.retrieve("pi_...", expand=["customer"])
print(intent.customer.email) | Use expand=['nested.field'] to retrieve full objects; by default Stripe returns only IDs. | stripe,expand,nested-objects |
11 | python | anthropic | system_in_messages | Response ignores instructions in messages role=system | messages = [{"role": "system", "content": "You are a concise assistant."}, {"role": "user", "content": "Explain quantum computing."}]
resp = client.messages.create(model="claude-opus-4-7", max_tokens=512, messages=messages) | Anthropic Messages API has a top-level system parameter — not a message with role='system'. | resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=512,
system="You are a concise assistant.",
messages=[{"role": "user", "content": "Explain quantum computing."}],
) | Pass system instructions via the top-level system= parameter, not as a message with role='system'. | anthropic,system-prompt |
12 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues") | The github API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,github |
13 | javascript | fetch | no_error_check | Silently receives 4xx/5xx without throwing | const resp = await fetch("https://api.sendgrid.com/v3/mail/send");
const data = await resp.json(); | fetch() resolves even on HTTP errors from sendgrid. Status must be checked manually. | const resp = await fetch("https://api.sendgrid.com/v3/mail/send");
if (!resp.ok) throw new Error(`HTTP ${resp.status} from sendgrid`);
const data = await resp.json(); | fetch() only rejects on network failure; always check resp.ok for HTTP-level errors. | fetch,error-handling,sendgrid |
14 | python | boto3 | s3_upload_large | EntityTooLarge: Your proposed upload exceeds the maximum allowed size | s3.put_object(Bucket="mybucket", Key="largefile.bin", Body=large_bytes) | put_object has a 5 GB limit. Large files require multipart upload. | from boto3.s3.transfer import TransferConfig
config = TransferConfig(multipart_threshold=8 * 1024 * 1024)
s3.upload_file("largefile.bin", "mybucket", "largefile.bin", Config=config) | Use upload_file with TransferConfig(multipart_threshold=...) for files > 5 GB. | aws,s3,upload,multipart |
15 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.stripe.com/v1/charges") | The stripe API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://api.stripe.com/v1/charges", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,stripe |
16 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", timeout=15)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,mapbox |
17 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.example.com/data")
print(resp.json()) | The request is missing authentication credentials. The API requires a Bearer token in the Authorization header. | headers = {"Authorization": "Bearer YOUR_TOKEN"}
resp = requests.get("https://api.example.com/data", headers=headers)
resp.raise_for_status()
print(resp.json()) | Always attach auth headers explicitly; requests does not add them automatically. | auth,http,401 |
18 | python | boto3 | region_missing | EndpointResolutionError: endpoint could not be resolved | import boto3
client = boto3.client("bedrock-runtime") # no region | Some AWS services (like Bedrock) require an explicit region. | import boto3
client = boto3.client("bedrock-runtime", region_name="us-east-1") | Always specify region_name for regional AWS services; the SDK default may not support the service. | aws,region,boto3 |
19 | go | net/http | http_status_not_checked | Silent error: 404 treated as success | resp, _ := http.Get("https://api.example.com/users/99")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body) | HTTP status code is not checked; 404 or 500 responses are silently treated as success. | resp, err := http.Get("https://api.example.com/users/99")
if err != nil { log.Fatal(err) }
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatalf("unexpected status: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body) | Always check resp.StatusCode after a successful Do/Get; network success != HTTP success. | go,http,error-handling |
20 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", timeout=60)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,mapbox |
21 | javascript | fetch | credential_cookies | Cookies not sent on cross-origin requests | const resp = await fetch("https://api.example.com/profile"); | By default fetch does not send cookies for cross-origin requests. | const resp = await fetch("https://api.example.com/profile", { credentials: "include" });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json(); | Set credentials: 'include' to send cookies cross-origin; also requires server CORS Allow-Credentials. | fetch,cookies,credentials,cors |
22 | python | redis | cache_stampede | Cache stampede: all workers recompute on cache miss simultaneously | val = r.get("expensive_result")
if val is None:
val = compute_expensive_result()
r.set("expensive_result", val, ex=300) | Many workers miss simultaneously and all start computing, overloading the backend. | import time
LOCK_KEY = "expensive_result:lock"
val = r.get("expensive_result")
if val is None:
if r.set(LOCK_KEY, "1", nx=True, ex=30):
try:
val = compute_expensive_result()
r.set("expensive_result", val, ex=300)
finally:
r.delete(LOCK_KEY)
else:
time.... | Use a Redis SETNX lock to allow only one worker to recompute on cache miss; others wait or serve stale. | redis,cache,stampede,locking |
23 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | The msgraph API requires authentication via X-API-Key header. | headers = {"X-API-Key": "X-API-Key: {API_KEY}"}
resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", headers=headers)
resp.raise_for_status() | Attach credentials in X-API-Key header; requests does not add them automatically. | auth,401,msgraph |
24 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,msgraph |
25 | python | requests | json_body | 415 Unsupported Media Type | payload = {"name": "alice", "role": "admin"}
resp = requests.post("https://api.example.com/users", data=payload) | data= sends form-encoded body. The API expects JSON, so the Content-Type is wrong. | payload = {"name": "alice", "role": "admin"}
resp = requests.post("https://api.example.com/users", json=payload)
resp.raise_for_status() | Use json= not data= to send JSON; requests sets Content-Type automatically. | json,content-type,415 |
26 | python | boto3 | paginator_missing | Truncated results: only first 1000 S3 objects returned | resp = s3.list_objects_v2(Bucket="mybucket")
objects = resp["Contents"] | list_objects_v2 returns at most 1000 objects. Use a paginator for buckets with more. | paginator = s3.get_paginator("list_objects_v2")
objects = []
for page in paginator.paginate(Bucket="mybucket"):
objects.extend(page.get("Contents", [])) | Use boto3 paginators for any list operation that may return more than 1000 results. | aws,s3,pagination |
27 | python | aiohttp | concurrent_requests | Sequential async calls — no performance gain | async def fetch_all(urls):
results = []
for url in urls:
resp = await session.get(url)
results.append(await resp.json())
return results | Sequential awaits defeat the purpose of async. Use asyncio.gather for concurrent requests. | async def fetch_all(urls, session):
async def fetch_one(url):
resp = await session.get(url)
resp.raise_for_status()
return await resp.json()
return await asyncio.gather(*[fetch_one(url) for url in urls]) | Use asyncio.gather() to run independent async requests concurrently. | aiohttp,async,concurrent,asyncio |
28 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | No timeout set on call to twilio endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", timeout=5)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,twilio |
29 | python | google-auth | no_credentials | google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials | import googleapiclient.discovery
service = googleapiclient.discovery.build("calendar", "v3") | No Application Default Credentials found. Point to the service account key file explicitly. | from google.oauth2 import service_account
import googleapiclient.discovery
creds = service_account.Credentials.from_service_account_file(
"service-account-key.json",
scopes=["https://www.googleapis.com/auth/calendar.readonly"],
)
service = googleapiclient.discovery.build("calendar", "v3", credentials=creds) | Use service_account.Credentials.from_service_account_file() for server-side auth. | google,auth,service-account |
30 | python | requests | json_body | 415 Unsupported Media Type | payload = {"key": "value"}
resp = requests.post("https://api.openai.com/v1/embeddings", data=payload) | data= sends form-encoded body to openai-rest. Use json= for JSON requests. | payload = {"key": "value"}
resp = requests.post("https://api.openai.com/v1/embeddings", json=payload)
resp.raise_for_status() | Use json= not data= to send JSON; requests sets Content-Type automatically. | json,content-type,415,openai-rest |
31 | python | requests | json_body | 415 Unsupported Media Type | payload = {"key": "value"}
resp = requests.post("https://graph.microsoft.com/v1.0/me/messages", data=payload) | data= sends form-encoded body to msgraph. Use json= for JSON requests. | payload = {"key": "value"}
resp = requests.post("https://graph.microsoft.com/v1.0/me/messages", json=payload)
resp.raise_for_status() | Use json= not data= to send JSON; requests sets Content-Type automatically. | json,content-type,415,msgraph |
32 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.sendgrid.com/v3/mail/send") | The sendgrid API requires authentication via X-API-Key header. | headers = {"X-API-Key": "X-API-Key: {API_KEY}"}
resp = requests.get("https://api.sendgrid.com/v3/mail/send", headers=headers)
resp.raise_for_status() | Attach credentials in X-API-Key header; requests does not add them automatically. | auth,401,sendgrid |
33 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | No timeout set on call to twilio endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", timeout=30)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,twilio |
34 | python | requests | ssl_verify_false | requests.exceptions.SSLError: certificate verify failed | resp = requests.get("https://internal-dev.example.com/api", verify=False) | Disabling SSL verification is insecure. The dev server has a self-signed cert that should be trusted explicitly. | resp = requests.get("https://internal-dev.example.com/api", verify="/path/to/dev-ca.crt")
resp.raise_for_status() | Pass verify='/path/to/ca-bundle.crt' instead of verify=False to trust self-signed certs securely. | ssl,security |
35 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.openai.com/v1/embeddings") | No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.openai.com/v1/embeddings", timeout=30)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,openai-rest |
36 | java | okhttp | network_on_main_thread | NetworkOnMainThreadException on Android | OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://api.example.com/data").build();
Response response = client.newCall(request).execute(); | Synchronous HTTP calls on Android main thread throw NetworkOnMainThreadException. | OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://api.example.com/data").build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) { /* handle */ }
@Override public void onResponse(Call call, Response response... | Use .enqueue() for async HTTP on Android; never block the main thread with .execute(). | java,android,okhttp,main-thread |
37 | python | anthropic | prompt_caching | High latency on repeated identical system prompts | resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=512,
system="You are a helpful assistant. " + LONG_CONTEXT,
messages=messages,
) | Large repeated system prompts incur full processing cost each time. Use prompt caching. | resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=512,
system=[{"type": "text", "text": "You are a helpful assistant. " + LONG_CONTEXT, "cache_control": {"type": "ephemeral"}}],
messages=messages,
) | Add cache_control: {type: ephemeral} to large static system prompt blocks to enable Anthropic prompt caching. | anthropic,prompt-caching,performance |
38 | python | aiohttp | session_per_request | DeprecationWarning: Unclosed client session | async def fetch(url):
session = aiohttp.ClientSession()
resp = await session.get(url)
return await resp.json() | Creating a new ClientSession per request opens new connections and leaks resources. | async def main():
async with aiohttp.ClientSession() as session:
resp = await session.get("https://api.example.com/data")
resp.raise_for_status()
return await resp.json() | Create one aiohttp.ClientSession for the app lifetime; use async with to close it properly. | aiohttp,async,session,resource-leak |
39 | python | httpx | client_not_closed | ResourceWarning: unclosed <AsyncClient> | client = httpx.AsyncClient()
resp = await client.get("https://api.example.com/data") | The AsyncClient is never closed, leaking connection resources. | async with httpx.AsyncClient() as client:
resp = await client.get("https://api.example.com/data")
resp.raise_for_status() | Always use httpx.AsyncClient as an async context manager to ensure connections are released. | httpx,resource-leak,async |
40 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.stripe.com/v1/charges") | The stripe API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://api.stripe.com/v1/charges", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,stripe |
41 | go | net/http | custom_transport | All connections share the same idle timeout unexpectedly | client := &http.Client{} | The default Transport uses global settings. For per-client control, create a custom Transport. | client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
},
} | Configure a custom http.Transport per client for fine-grained control over connection pooling and TLS. | go,http,transport,performance |
42 | javascript | axios | transformResponse | Response data not parsed as expected type | const resp = await axios.get("https://api.example.com/count");
console.log(typeof resp.data); // "string" not "number" | axios parses JSON by default but may fail for unusual content types. Use transformResponse. | const resp = await axios.get("https://api.example.com/count", {
transformResponse: [(data) => parseInt(data, 10)]
});
console.log(typeof resp.data); // "number" | Use transformResponse to post-process the raw response string into the desired type. | axios,transformResponse,types |
43 | rest | generic | http_verbs_misuse | State change via GET causes side effects on caching/replay | GET /api/users/42/delete
# Logs out user when link is prefetched by browser | GET must be safe and idempotent; side effects via GET break caching, prefetch, and crawlers. | DELETE /api/users/42
# Or: POST /api/users/42/deactivate | Use DELETE/POST/PUT for state-changing operations; GET must be safe and idempotent. | rest,http-verbs,semantics |
44 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.openai.com/v1/embeddings") | No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.openai.com/v1/embeddings", timeout=5)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,openai-rest |
45 | go | net/http | no_context_timeout | http.Get blocks forever on slow server | resp, err := http.Get("https://slow-api.example.com/data") | The default http.Get has no timeout. Use a context with deadline. | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://slow-api.example.com/data", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil { log.Fatal(err) }
defer resp.Body.Close() | Use http.NewRequestWithContext with context.WithTimeout; bare http.Get has no deadline. | go,http,timeout,context |
46 | python | stripe | idempotency_key_retry | Duplicate charge on network retry | stripe.PaymentIntent.create(amount=1000, currency="usd") | Without an idempotency key a retried request creates a second PaymentIntent. | import uuid
stripe.PaymentIntent.create(
amount=1000,
currency="usd",
idempotency_key=str(uuid.uuid4()),
) | Generate a UUID per payment action and reuse it on retries; Stripe deduplicates by this key. | stripe,idempotency,payments |
47 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.sendgrid.com/v3/mail/send") | No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.sendgrid.com/v3/mail/send", timeout=60)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,sendgrid |
48 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.sendgrid.com/v3/mail/send") | No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.sendgrid.com/v3/mail/send", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,sendgrid |
49 | python | stripe | webhook_raw_bytes | stripe.error.SignatureVerificationError: No signatures found matching | payload = request.data
sig = request.headers["Stripe-Signature"]
event = stripe.Webhook.construct_event(payload, sig, "whsec_...") | The raw bytes must be passed, not a parsed JSON string. | payload = request.get_data(as_text=False) # raw bytes
sig = request.headers["Stripe-Signature"]
try:
event = stripe.Webhook.construct_event(payload, sig, os.environ["STRIPE_WEBHOOK_SECRET"])
except stripe.error.SignatureVerificationError:
return "Invalid signature", 400 | Stripe webhook validation requires raw request bytes; never pass a decoded/parsed body. | stripe,webhook,signature |
50 | python | boto3 | no_credentials | botocore.exceptions.NoCredentialsError: Unable to locate credentials | import boto3
s3 = boto3.client("s3")
s3.list_buckets() | No AWS credentials configured. boto3 searches env vars, ~/.aws/credentials, and IAM roles. | import boto3, os
s3 = boto3.client(
"s3",
aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"],
region_name="us-east-1",
)
s3.list_buckets() | Provide credentials via environment variables or ~/.aws/credentials; never hard-code them in source. | aws,credentials,boto3 |
51 | typescript | react-query | error_boundary | Unhandled error crashes the whole React tree | const { data } = useQuery(["posts"], fetchPosts);
return <PostList posts={data} />; | Query errors are not surfaced; if fetchPosts throws, data is undefined and the component crashes. | const { data, isError, error } = useQuery(["posts"], fetchPosts);
if (isError) return <ErrorMessage message={error.message} />;
return <PostList posts={data ?? []} />; | Always destructure isError and error from useQuery and render an error state; don't assume data is defined. | react-query,typescript,error-handling |
52 | python | redis | new_connection_per_call | redis.exceptions.ConnectionError: max number of clients reached | def handler(event):
r = redis.Redis(host="localhost", port=6379)
r.set("key", "value") | Creating a new Redis client per request creates a new connection each time. | pool = redis.ConnectionPool(host="localhost", port=6379, max_connections=20)
def handler(event):
r = redis.Redis(connection_pool=pool)
r.set("key", "value") | Create one ConnectionPool at startup and share it across handlers. | redis,connection-pool,performance |
53 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | The msgraph API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,msgraph |
54 | python | openai | function_calling_history | openai.BadRequestError: messages does not contain assistant turn after tool_call | messages = [{"role": "user", "content": "What is the weather?"}]
resp = client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
tool_call = resp.choices[0].message.tool_calls[0]
result_msg = {"role": "tool", "content": json.dumps(weather), "tool_call_id": tool_call.id}
resp2 = client.chat.complet... | The tool result turn must include the full prior conversation including the assistant tool_calls message. | messages = [{"role": "user", "content": "What is the weather?"}]
resp = client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
messages.append(resp.choices[0].message) # keep assistant turn
tool_call = resp.choices[0].message.tool_calls[0]
messages.append({"role": "tool", "content": json.dumps(... | Always append the assistant message (with tool_calls) to history before adding the tool result. | openai,function-calling,tool-use |
55 | python | grpc | insecure_channel | grpc._channel._InactiveRpcError: StatusCode.UNAVAILABLE — TLS required | channel = grpc.insecure_channel("api.example.com:443")
stub = MyServiceStub(channel) | The server requires TLS but an insecure channel was used. | creds = grpc.ssl_channel_credentials()
channel = grpc.secure_channel("api.example.com:443", creds)
stub = MyServiceStub(channel) | Use grpc.secure_channel() with ssl_channel_credentials() for TLS-required gRPC endpoints. | grpc,tls,ssl |
56 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | No timeout set on call to twilio endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,twilio |
57 | python | httpx | follow_redirects_off | 301 response returned instead of final destination | import httpx
resp = httpx.get("http://api.example.com/data") | httpx does not follow redirects by default (unlike requests). | import httpx
resp = httpx.get("http://api.example.com/data", follow_redirects=True)
resp.raise_for_status() | httpx requires follow_redirects=True explicitly; requests follows redirects by default. | redirect,httpx |
58 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.stripe.com/v1/charges") | No timeout set on call to stripe endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.stripe.com/v1/charges", timeout=15)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,stripe |
59 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.openai.com/v1/embeddings") | The openai-rest API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://api.openai.com/v1/embeddings", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,openai-rest |
60 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | The twilio API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,twilio |
61 | javascript | fetch | json_body_wrong | 415 Unsupported Media Type when POSTing JSON | const resp = await fetch("https://api.example.com/users", {
method: "POST",
body: { name: "alice" }, // object, not string
}); | The body must be a JSON string and Content-Type must be set explicitly. | const resp = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "alice" }),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json(); | Stringify the body with JSON.stringify() and set Content-Type: application/json header manually. | fetch,json,content-type,415 |
62 | rest | generic | breaking_versioning | Breaking change: v1 clients crash after API field rename | GET /api/users -> {"username": "alice"}
# Changed to:
GET /api/users -> {"login": "alice"} # breaks all clients | Field renaming without versioning breaks all existing clients. | GET /api/v1/users -> {"username": "alice"} # unchanged
GET /api/v2/users -> {"login": "alice"} # new version | Never rename or remove fields without bumping the API version; prefer additive changes. | rest,versioning,backward-compat |
63 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.stripe.com/v1/charges") | No timeout set on call to stripe endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.stripe.com/v1/charges", timeout=30)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,stripe |
64 | python | openai | json_mode | json.JSONDecodeError when parsing model output | resp = client.chat.completions.create(model="gpt-4o", messages=[{"role":"user","content":"Return JSON with name and age"}])
data = json.loads(resp.choices[0].message.content) | Without json mode, the model may include markdown fences or explanatory text around the JSON. | resp = client.chat.completions.create(
model="gpt-4o",
messages=[{"role":"user","content":"Return JSON with name and age"}],
response_format={"type": "json_object"},
)
data = json.loads(resp.choices[0].message.content) | Use response_format={'type': 'json_object'} to guarantee the model returns valid JSON without extra text. | openai,json-mode,structured-output |
65 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,mapbox |
66 | python | gql | n_plus_one_queries | N+1 queries: fetching list then querying each item individually | users = client.execute(gql("query { users { id } }"))
for u in users["users"]:
detail = client.execute(gql(f'query {{ user(id: {u["id"]}) {{ name email }} }}')) | One query per user makes N+1 round trips. Request nested fields in one query instead. | result = client.execute(gql("query { users { id name email } }"))
for user in result["users"]:
process(user) | Fetch nested fields in a single GraphQL query; avoid N+1 query patterns. | graphql,n-plus-one,performance |
67 | go | net/http | post_no_content_type | 415 Unsupported Media Type on POST | body := strings.NewReader(`{"name":"alice"}`)
resp, err := http.Post("https://api.example.com/users", "", body) | The Content-Type argument is empty. The API expects application/json. | body := strings.NewReader(`{"name":"alice"}`)
resp, err := http.Post("https://api.example.com/users", "application/json", body)
if err != nil { log.Fatal(err) }
defer resp.Body.Close() | Always pass "application/json" as the content-type argument to http.Post. | go,http,json,content-type |
68 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.slack.com/api/chat.postMessage") | The slack API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://api.slack.com/api/chat.postMessage", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,slack |
69 | python | requests | pagination_keyerror | KeyError: 'next' | url = "https://api.example.com/items"
while True:
resp = requests.get(url).json()
process(resp["items"])
url = resp["next"] # KeyError on last page | The last page has no 'next' key but the code accesses it unconditionally. | url = "https://api.example.com/items"
while url:
resp = requests.get(url).json()
process(resp["items"])
url = resp.get("next") # None on last page -> loop ends | Use .get('next') which returns None when the key is absent, terminating the loop cleanly. | pagination,KeyError |
70 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", timeout=15)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,msgraph |
71 | javascript | fetch | no_error_check | Silently receives 4xx/5xx without throwing | const resp = await fetch("https://graph.microsoft.com/v1.0/me/messages");
const data = await resp.json(); | fetch() resolves even on HTTP errors from msgraph. Status must be checked manually. | const resp = await fetch("https://graph.microsoft.com/v1.0/me/messages");
if (!resp.ok) throw new Error(`HTTP ${resp.status} from msgraph`);
const data = await resp.json(); | fetch() only rejects on network failure; always check resp.ok for HTTP-level errors. | fetch,error-handling,msgraph |
72 | javascript | axios | token_refresh_interceptor | 401 after token expiry — user sees error instead of auto-refresh | const resp = await api.get("/protected"); | The token expired mid-session. An axios response interceptor can refresh it transparently. | api.interceptors.response.use(
res => res,
async err => {
if (err.response?.status === 401 && !err.config._retry) {
err.config._retry = true;
const token = await refreshAccessToken();
api.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return... | Axios response interceptors can catch 401, refresh the token, and replay the original request. | axios,interceptor,auth,refresh-token |
73 | python | requests | json_body | 415 Unsupported Media Type | payload = {"key": "value"}
resp = requests.post("https://api.sendgrid.com/v3/mail/send", data=payload) | data= sends form-encoded body to sendgrid. Use json= for JSON requests. | payload = {"key": "value"}
resp = requests.post("https://api.sendgrid.com/v3/mail/send", json=payload)
resp.raise_for_status() | Use json= not data= to send JSON; requests sets Content-Type automatically. | json,content-type,415,sendgrid |
74 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.openai.com/v1/embeddings") | The openai-rest API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://api.openai.com/v1/embeddings", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,openai-rest |
75 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.openai.com/v1/embeddings") | No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.openai.com/v1/embeddings", timeout=15)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,openai-rest |
76 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", timeout=5)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,msgraph |
77 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | The mapbox API requires authentication via X-API-Key header. | headers = {"X-API-Key": "X-API-Key: {API_KEY}"}
resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", headers=headers)
resp.raise_for_status() | Attach credentials in X-API-Key header; requests does not add them automatically. | auth,401,mapbox |
78 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.stripe.com/v1/charges") | No timeout set on call to stripe endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.stripe.com/v1/charges", timeout=5)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,stripe |
79 | python | anthropic | streaming_await_error | TypeError: object Message cannot be used in await expression | async with client.messages.stream(model="claude-opus-4-7", max_tokens=512, messages=msgs) as stream:
resp = await stream # wrong | The stream context manager yields an event stream; you iterate it, not await the whole object. | async with client.messages.stream(
model="claude-opus-4-7",
max_tokens=512,
messages=[{"role": "user", "content": "Tell me a story."}],
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True) | Use async for text in stream.text_stream to consume streaming tokens; do not await the stream itself. | anthropic,streaming,async |
80 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.sendgrid.com/v3/mail/send") | No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.sendgrid.com/v3/mail/send", timeout=15)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,sendgrid |
81 | python | boto3 | dynamodb_decimal | TypeError: Float types are not supported. Use Decimal types instead. | table.put_item(Item={"id": "1", "score": 9.5}) | DynamoDB does not accept Python float; use Decimal from the decimal module. | from decimal import Decimal
table.put_item(Item={"id": "1", "score": Decimal("9.5")}) | DynamoDB requires Decimal (not float) for numeric values; convert floats with Decimal(str(value)). | aws,dynamodb,decimal,types |
82 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", timeout=30)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,mapbox |
83 | python | requests | multipart_upload | 400 Bad Request: expected multipart/form-data | with open("image.png", "rb") as f:
resp = requests.post("https://api.example.com/upload", data=f) | Sending raw bytes via data= doesn't set multipart boundaries. Use files= for multipart upload. | with open("image.png", "rb") as f:
resp = requests.post("https://api.example.com/upload", files={"file": ("image.png", f, "image/png")})
resp.raise_for_status() | Use files={} for multipart/form-data uploads; it sets the correct Content-Type with boundary automatically. | multipart,upload,requests |
84 | typescript | react-query | mutation_invalidation | Stale data shown after successful mutation | const mutation = useMutation(updateUser);
mutation.mutate(payload); // cache not refreshed | After a mutation, query cache must be invalidated to trigger a refetch. | const queryClient = useQueryClient();
const mutation = useMutation(updateUser, {
onSuccess: () => {
queryClient.invalidateQueries(["user"]);
},
});
mutation.mutate(payload); | Use onSuccess + queryClient.invalidateQueries() to refresh stale data after mutations. | react-query,typescript,mutation,invalidation |
85 | javascript | fetch | cors_blocked | Access blocked by CORS policy | const resp = await fetch("https://api.example.com/data");
const data = await resp.json(); | CORS is enforced by the browser. The fix is server-side or proxy via your backend. | // Proxy through your backend:
const resp = await fetch("/api/proxy/data");
const data = await resp.json(); | CORS cannot be fixed client-side; configure the target server or proxy via your own backend. | cors,browser,fetch |
86 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues") | No timeout set on call to github endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,github |
87 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/") | The mapbox API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,mapbox |
88 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues") | The github API requires authentication via Authorization header. | headers = {"Authorization": "Token {API_KEY}"}
resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,github |
89 | typescript | openai | structured_output | json.JSONDecodeError: model returned prose instead of JSON | const resp = await client.chat.completions.create({
model: "gpt-4o", messages: [{role:"user", content:"Extract: " + text}]
});
const data = JSON.parse(resp.choices[0].message.content!); | Without JSON mode or structured output, the model may include markdown or prose. | import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";
const schema = z.object({ name: z.string(), age: z.number() });
const resp = await client.beta.chat.completions.parse({
model: "gpt-4o",
messages: [{ role: "user", content: "Extract: " + text }],
response_format: zodResponseFo... | Use zodResponseFormat with client.beta.chat.completions.parse() for type-safe structured output. | typescript,openai,structured-output,zod |
90 | python | boto3 | waiter_usage | Checking EC2 instance state in a polling loop manually | import time
ec2.start_instances(InstanceIds=[instance_id])
while True:
state = ec2.describe_instances(InstanceIds=[instance_id])["Reservations"][0]["Instances"][0]["State"]["Name"]
if state == "running":
break
time.sleep(5) | Manual polling is fragile. boto3 provides built-in waiters for common state transitions. | ec2.start_instances(InstanceIds=[instance_id])
waiter = ec2.get_waiter("instance_running")
waiter.wait(InstanceIds=[instance_id]) | Use boto3 waiters instead of manual polling loops; they handle retries and timeouts correctly. | aws,ec2,waiter |
91 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | The twilio API requires authentication via X-API-Key header. | headers = {"X-API-Key": "X-API-Key: {API_KEY}"}
resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", headers=headers)
resp.raise_for_status() | Attach credentials in X-API-Key header; requests does not add them automatically. | auth,401,twilio |
92 | typescript | react-query | stale_time_missing | Excessive refetches on every component mount | const { data } = useQuery(["user", id], () => fetchUser(id)); | Without staleTime, react-query refetches on every mount and window focus. | const { data } = useQuery(
["user", id],
() => fetchUser(id),
{ staleTime: 5 * 60 * 1000 } // 5 minutes
); | Set staleTime to match the data freshness requirement; default 0 causes aggressive refetching. | react-query,typescript,stale-time,performance |
93 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.sendgrid.com/v3/mail/send") | No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.sendgrid.com/v3/mail/send", timeout=30)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,sendgrid |
94 | python | requests | json_body | 415 Unsupported Media Type | payload = {"key": "value"}
resp = requests.post("https://api.stripe.com/v1/charges", data=payload) | data= sends form-encoded body to stripe. Use json= for JSON requests. | payload = {"key": "value"}
resp = requests.post("https://api.stripe.com/v1/charges", json=payload)
resp.raise_for_status() | Use json= not data= to send JSON; requests sets Content-Type automatically. | json,content-type,415,stripe |
95 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.sendgrid.com/v3/mail/send") | The sendgrid API requires authentication via Authorization header. | headers = {"Authorization": "Bearer {TOKEN}"}
resp = requests.get("https://api.sendgrid.com/v3/mail/send", headers=headers)
resp.raise_for_status() | Attach credentials in Authorization header; requests does not add them automatically. | auth,401,sendgrid |
96 | python | requests | auth_missing | 401 Unauthorized | resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues") | The github API requires authentication via X-API-Key header. | headers = {"X-API-Key": "X-API-Key: {API_KEY}"}
resp = requests.get("https://api.github.com/repos/{owner}/{repo}/issues", headers=headers)
resp.raise_for_status() | Attach credentials in X-API-Key header; requests does not add them automatically. | auth,401,github |
97 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.openai.com/v1/embeddings") | No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.openai.com/v1/embeddings", timeout=10)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,openai-rest |
98 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | No timeout set on call to twilio endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", timeout=60)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,twilio |
99 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages") | No timeout set on call to twilio endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages", timeout=15)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,twilio |
100 | python | requests | timeout_missing | requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages") | No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely. | resp = requests.get("https://graph.microsoft.com/v1.0/me/messages", timeout=60)
resp.raise_for_status() | Always set a timeout on requests to external APIs; the default is None (wait forever). | timeout,requests,msgraph |
API Error Resolution Pairs
A synthetic dataset of real-world API error scenarios paired with explanations and fixes. Each example captures a broken code snippet, the error it produces, a plain-English explanation of the root cause, a corrected implementation, and a distilled key insight.
Dataset Summary
| Split | Examples |
|---|---|
| train | 132 |
| validation | 16 |
| test | 16 |
| Total | 164 |
Quick Start
Load the dataset
from datasets import load_dataset
ds = load_dataset("SalutefaceAAC/api-error-resolution-pairs")
print(ds)
# DatasetDict({
# train: Dataset({features: [...], num_rows: 132}),
# validation: Dataset({features: [...], num_rows: 16}),
# test: Dataset({features: [...], num_rows: 16})
# })
# Inspect a record
example = ds["train"][0]
print(example["error_type"]) # e.g. "timeout_missing"
print(example["broken_code"]) # code that triggers the error
print(example["fixed_code"]) # corrected implementation
print(example["key_insight"]) # one-sentence principle
Filter by language or error type
# All Python examples
py_examples = ds["train"].filter(lambda x: x["language"] == "python")
# Rate-limiting errors only
rate_limit = ds["train"].filter(lambda x: x["error_type"] == "rate_limit")
# Multi-filter: TypeScript + auth errors
ts_auth = ds["train"].filter(
lambda x: x["language"] == "typescript" and "auth" in x["error_type"]
)
RAG retrieval (semantic search over error patterns)
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer("all-MiniLM-L6-v2")
train = ds["train"]
# Embed error messages as the retrieval key
embeddings = model.encode(train["error_message"], show_progress_bar=True)
def find_similar(query: str, top_k: int = 3):
q_emb = model.encode([query])
scores = np.dot(embeddings, q_emb.T).squeeze()
top_idx = np.argsort(scores)[::-1][:top_k]
for i in top_idx:
print(f"[{scores[i]:.3f}] {train[int(i)]['error_type']} — {train[int(i)]['key_insight']}")
find_similar("Connection refused when calling external API")
Fine-tuning prompt template
def format_for_finetuning(example):
"""Format a record as an instruction-following prompt."""
prompt = (
f"Language: {example['language']}\n"
f"Library: {example['library']}\n"
f"Error: {example['error_message']}\n\n"
f"Broken code:\n```\n{example['broken_code']}\n```\n\n"
"Explain the root cause and provide the corrected implementation."
)
completion = (
f"Root cause: {example['explanation']}\n\n"
f"Fixed code:\n```\n{example['fixed_code']}\n```\n\n"
f"Key insight: {example['key_insight']}"
)
return {"prompt": prompt, "completion": completion}
formatted = ds["train"].map(format_for_finetuning)
Sample Records
Example 1 — Python / requests: Large file download (MemoryError)
| Field | Value |
|---|---|
language |
python |
library |
requests |
error_type |
stream_large_response |
error_message |
MemoryError downloading large file |
Broken code:
resp = requests.get("https://example.com/large-file.zip")
with open("large-file.zip", "wb") as f:
f.write(resp.content)
Fixed code:
resp = requests.get("https://example.com/large-file.zip", stream=True)
with open("large-file.zip", "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
Key insight: Use stream=True and iter_content() to download large files without loading them into memory.
Example 2 — JavaScript / axios: Unhandled cancellation
| Field | Value |
|---|---|
language |
javascript |
library |
axios |
error_type |
cancel_request |
error_message |
CanceledError unhandled when navigating away |
Broken code:
const source = axios.CancelToken.source();
axios.get("/slow-api", { cancelToken: source.token });
source.cancel();
Fixed code:
const controller = new AbortController();
try {
const resp = await axios.get("/slow-api", { signal: controller.signal });
process(resp.data);
} catch (err) {
if (!axios.isCancel(err)) throw err;
}
// to cancel: controller.abort();
Key insight: Use AbortController with axios (v1+) and filter cancellations with axios.isCancel(err).
Example 3 — REST: Content negotiation failure
| Field | Value |
|---|---|
language |
rest |
library |
generic |
error_type |
content_negotiation |
error_message |
406 Not Acceptable |
Broken request:
GET /api/data
Accept: text/html
Fixed request:
GET /api/data
Accept: application/json
Key insight: Match the Accept header to the media types the server advertises.
Schema
| Field | Type | Description |
|---|---|---|
id |
int | Unique record identifier |
language |
string | Programming language (python, javascript, typescript, go, java, rest) |
library |
string | Library or framework (requests, httpx, boto3, openai, anthropic, fetch, axios, okhttp, net/http, …) |
error_type |
string | Short error category slug |
error_message |
string | The actual error message or symptom |
broken_code |
string | Snippet that triggers the error |
explanation |
string | Root cause explanation |
fixed_code |
string | Corrected implementation |
key_insight |
string | One-sentence principle to prevent this class of error |
tags |
string | Comma-separated tag list |
Coverage
Languages & Libraries
| Language | Libraries |
|---|---|
| Python | requests, httpx, boto3, openai, anthropic, aiohttp, grpc, gql, stripe, google-auth, redis |
| JavaScript | fetch, axios |
| TypeScript | openai, react-query |
| Go | net/http |
| Java | okhttp |
| REST | Generic HTTP patterns |
Error Categories
- Auth: missing/malformed credentials, 401 flows
- Timeout: missing timeouts, context deadlines
- JSON body: wrong encoding, missing Content-Type
- Error handling: unchecked 4xx/5xx, silent failures
- Rate limiting: 429, Retry-After, backoff
- Pagination: offset vs cursor, last-page edge cases
- Resource leaks: unclosed bodies, sessions, connections
- SSL/TLS: certificate verification, insecure channels
- Performance: connection pools, pipelines, parallel requests
- Streaming: async iteration, chunk handling
- Function/tool calling: history management, tool result format
- Structured output: JSON mode, Zod schemas
- Idempotency: duplicate charges, retry safety
- Versioning: breaking changes, additive vs destructive
Generation Methodology
Records were hand-authored one at a time, each capturing a distinct error pattern from real developer experience. A parametric augmentation layer generates variants across different API endpoints, token formats, and timeout values to increase dataset breadth without noise. All records passed MD5-based deduplication (keyed on broken_code + fixed_code).
No model was used to generate records. All broken_code / fixed_code / explanation / key_insight values were written manually.
Intended Uses
- Fine-tuning code LLMs on error diagnosis and remediation
- Retrieval-augmented code assistance (RAG over error patterns)
- Benchmark evaluation for debugging models
- Developer education tooling
Limitations
- Augmentation depth: parametric augmentation varies endpoints and timeout values only — augmented records share structure with their base and increase breadth but not conceptual depth.
- Language coverage: Java examples focus on Android context (OkHttp); server-side Java (Spring, Quarkus) patterns are underrepresented. Go examples cover
net/httponly. - Scenario complexity: each record is a single-error / single-fix scenario. Multi-step debugging chains and cascading failures are out of scope.
- Domain scope: covers mainstream REST and gRPC clients; WebSocket, GraphQL subscriptions, and binary protocols are not included.
- No runtime validation: code snippets are validated by human review, not executed; edge-case compilation issues may exist.
License
Apache 2.0
Citation
@dataset{saluteface_api_error_resolution_2026,
title = {API Error Resolution Pairs},
author = {SalutefaceAAC},
year = {2026},
url = {https://huggingface.co/datasets/SalutefaceAAC/api-error-resolution-pairs}
}
- Downloads last month
- 75