API Design · question
Question 30 of 110
How should you structure error responses in APIs?
Related concept
Status codes and error design: how an API says NO
The status code tells machines whose fault the failure was and whether to retry. The error body tells a developer what to fix, and it is never an apology.
For this question · chapter 2 of 3
2/3
Error parts go to their fields
Error parts go to their fields
- The status code is for machines. The body is for the person who has to fix the problem. Here the code is 422, which is correct, so the client takes the error path. But the body only says something went wrong. So the message helps nobody: not the client, not the user, and not the API owner (you).
- The error body contains a code, VALIDATION_ERROR, and the client matches that exact string. The code exists for branching, so the wording never changes and the code is never a sentence. Treat the code like an enum you have published. Clients depend on the code from the day it ships.
- The message is written for a person: email and password are invalid. No client logic should depend on the message, so you may reword the message at any time. The message is for a developer reading a log. The error code is for a program.
- The details list has two entries, email and password. Each entry names its field, so the form can show the error where the user is looking. A validation error with no field name does not say where the problem is. So the user has to search the form for the field that is wrong.
- The error body carries a request id. The log line records the same id next to the error message. Support asks for that id, because the id links a complaint in a ticket to a line in your logs. You search by timestamp when the id is missing.
- The error body should never include a stack trace. Internal details such as file paths, SQL, and driver messages are not transparency. Those details show an attacker what runs behind the API. RFC 9457, called problem details, is the standard to cite if you want one.
Chapter 2 · step 1 of 6
The status code is for machines. The body is for the person who has to fix the problem. Here the code is 422, which is correct, so the client takes the error path. But the body only says something went wrong. So the message helps nobody: not the client, not the user, and not the API owner (you).
© LearnThatStack - diagrams may not be republished without permission.
Want a quick review of the fundamentals? See the API Design cheatsheet.
Pro · $10/mo
90 of 110 API Design answers are in Pro.
Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.
- Full answers + code
- AI explanations, simpler or deeper
- 1,000 AI credits / month
- Cancel anytime