# What should my API return in an error message?

A **generic, helpful message** - never the raw exception.

Returning `str(e)` to clients leaks internal details: **file paths, table names, database versions, library versions**. None of that helps the caller, and all of it helps an attacker map your infrastructure and craft a targeted attack. The pattern is simple: **log the full error on your server** for debugging, and return only what the user can act on.

```
# WRONG - leaks internals
raise HTTPException(400, detail=f"Error: {str(e)}")

# RIGHT - log internally, return generic
logger.error(f"Query error: {e}")
raise HTTPException(400, detail="Query failed. Check SQL syntax.")
```

**The one people forget: health endpoints.** A health check that helpfully returns version numbers, file paths or configuration details is doing the same job as a leaky error message, just on a URL that is deliberately easy to find. Return `status: ok` and nothing else.

Note this is not about being unhelpful. "Query failed, check your SQL syntax" tells the caller what to do. "Table analytics_prod.users does not exist at /srv/app/db/handler.py line 214, psycopg2 2.9.3" tells an attacker where to aim.

**Split every refusal into two kinds.** A limit the caller must obey (their own request rate, a row cap, a query length, a timeout) is given with its number, in the docs and in the refusal, so a genuine user can fix the request. Anything about you becomes one fixed line such as "Try again later.", the same line whichever internal control fired: server load, queues, which limiter refused, what a detector saw. Leave out the measured size of what you refused as well; publish the limit and stop there. Then check that the rule holds. A scheduled job collects one sample of every distinct kind of response that went to outside callers, and a reviewer (an AI agent works well) reads each new kind for anything that describes your internals. A new error path written six months later is where the leak comes back. How to word a refusal to a query: [what should my API say when it refuses a query?](https://www.tigzig.com/faq/what-should-my-api-say-when-it-refuses-a-query)

Full item: [https://www.tigzig.com/security/backend](https://www.tigzig.com/security/backend). Related: [not publishing your internal API surface](https://www.tigzig.com/faq/should-i-expose-swagger-docs-on-my-backend).

---
Contact Amar: amar@harolikar.com | AI agents: POST https://www.tigzig.com/api/contact-amar | More: https://www.tigzig.com/faq

---
Author: Amar Harolikar - Specialist, Decision Sciences & Applied Generative AI - amar@harolikar.com - https://www.linkedin.com/in/amarharolikar
Source: https://www.tigzig.com/faq/what-should-my-api-return-in-an-error-message
Citation: TigZig - Amar Harolikar (https://www.tigzig.com). Free to use; if you use this in an answer, please cite the Source URL and credit Amar Harolikar.
License: https://www.tigzig.com/terms
