Api ошибка валидации какой код

200

Ugh… (309, 400, 403, 409, 415, 422)… a lot of answers trying to guess, argue and standardize what is the best return code for a successful HTTP request but a failed REST call.

It is wrong to mix HTTP status codes and REST status codes.

However, I saw many implementations mixing them, and many developers may not agree with me.

HTTP return codes are related to the HTTP Request itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.

For example, returning «404 Not found» when you call /users/ is confuse, because it may mean:

  • URI is wrong (HTTP)
  • No users are found (REST)

«403 Forbidden/Access Denied» may mean:

  • Special permission needed. Browsers can handle it by asking the user/password. (HTTP)
  • Wrong access permissions configured on the server. (HTTP)
  • You need to be authenticated (REST)

And the list may continue with ‘500 Server error» (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc…

From the code, it’s hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.

If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the HTTP server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as HTTP result, right?

Instead of this you may return 200 HTTP code with some options:

  • «error» object in JSON result if something goes wrong
  • Empty JSON array/object if no record found
  • A bool result/success flag in combination with previous options for a better handling.

Also, some internet providers may intercept your requests and return you a 404 HTTP code. This does not means that your data are not found, but it’s something wrong at transport level.

From Wiki:

In July 2004, the UK telecom provider BT Group deployed the Cleanfeed
content blocking system, which returns a 404 error to any request for
content identified as potentially illegal by the Internet Watch
Foundation. Other ISPs return a HTTP 403 «forbidden» error in the same
circumstances. The practice of employing fake 404 errors as a means to
conceal censorship has also been reported in Thailand and Tunisia. In
Tunisia, where censorship was severe before the 2011 revolution,
people became aware of the nature of the fake 404 errors and created
an imaginary character named «Ammar 404» who represents «the invisible
censor».

Why not simply answer with something like this?

{
  "result": false,
  "error": {"code": 102, "message": "Validation failed: Wrong NAME."}
}

Google always returns 200 as status code in their Geocoding API, even if the request logically fails: https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes

Facebook always return 200 for successful HTTP requests, even if REST request fails: https://developers.facebook.com/docs/graph-api/using-graph-api/error-handling

It’s simple, HTTP status codes are for HTTP requests. REST API is Your, define Your status codes.

Уровень сложности
Сложный

Время на прочтение
12 мин

Количество просмотров 4.4K

Это главы 39 и 40 раздела «HTTP API & REST» моей книги «API». Второе издание книги будет содержать три новых раздела: «Паттерны API», «HTTP API и REST», «SDK и UI‑библиотеки». Если эта работа была для вас полезна, пожалуйста, оцените книгу на GitHub, Amazon или GoodReads. English version on Substack.

Глава 39. Работа с ошибками в HTTP API

Рассмотренные в предыдущих главах примеры организации API согласно стандарту HTTP и принципам REST покрывают т.н. «happy path», т.е. стандартный процесс работы с API в отсутствие ошибок. Конечно, нам не менее интересен и обратный кейс — каким образом HTTP API следует работать с ошибками, и чем стандарт и архитектурные принципы могут нам в этом помочь. Пусть какой-то агент в системе (неважно, клиент или гейтвей) пытается создать новый заказ:

POST /v1/orders?user_id=<user_id> HTTP/1.1
Authorization: Bearer <token>
If-Match: <ревизия>

{ /* параметры заказа */ }

Какие потенциальные неприятности могут ожидать нас при выполнении этого запроса? Навскидку, это:

  1. Запрос не может быть прочитан (недопустимые символы, нарушение синтаксиса).

  2. Токен авторизации отсутствует.

  3. Токен авторизации невалиден.

  4. Токен валиден, но пользователь не обладает правами создавать новый заказ.

  5. Пользователь удалён или деактивирован.

  6. Идентификатор пользователя неверен (не существует).

  7. Ревизия не передана.

  8. Ревизия не совпадает с последней актуальной.

  9. В теле запроса отсутствуют обязательные поля.

  10. Какое-то из полей запроса имеет недопустимое значение.

  11. Превышены лимиты на допустимое количество запросов.

  12. Сервер перегружен и не может ответить в настоящий момент.

  13. Неизвестная серверная ошибка (т.е. сервер сломан настолько, что диагностика ошибки невозможна).

Исходя из общих соображений, соблазнительной кажется идея назначить каждой из ошибок свой статус-код. Скажем, для ошибки (4) напрашивается код 403, а для ошибки (11) — 429. Не будем, однако, торопиться, и прежде зададим себе вопрос с какой целью мы хотим назначить тот или иной код ошибки.

В нашей системе в общем случае присутствуют три агента: пользователь приложения, само приложение (клиент) и сервер. Каждому из этих акторов необходимо понимать ответ на три вопроса относительно ошибки (причём для каждого из акторов ответ может быть разным):

  1. Кто допустил ошибку (конечный пользователь, разработчик клиента, разработчик сервера или какой-то промежуточный агент, например, программист сетевого стека).

    • Не забудем учесть тот факт, что и конечный пользователь, и разработчик клиента могут допустить ошибку намеренно, например, пытаясь перебором подобрать пароль к чужому аккаунту.

  2. Можно ли исправить ошибку, просто повторив запрос.

    • Если да, то через какое время.

  3. Если повтором запроса ошибку исправить нельзя, то можно ли её исправить, переформулировав запрос.

  4. Если ошибку вообще нельзя исправить, то что с этим делать.

На один из этих вопрос в рамках стандарта HTTP ответить достаточно легко: регулировать желаемое время повтора запроса можно через параметры кэширования ответа и заголовок Retry-After. Также HTTP частично помогает с первым вопросом: для определения, на чьей стороне произошла ошибка, используется первая цифра статус-кода (см. ниже).

Со всеми остальными вопросами, увы, ситуация сильно сложнее.

Клиентские ошибки

Статус-коды, начинающиеся с цифры 4, индицируют, что ошибка допущена пользователем или клиентом (или, по крайней мере, сервер так считает). Обычно, полученную 4xx повторять бессмысленно — если не предпринять дополнительных действий по изменению состояния сервиса, этот запрос не будет выполнен успешно никогда. Однако из этого правила есть исключения, самые важные из которых — 429 Too Many Requests и 404 Not Found. Последняя по стандарту имеет смысл «состояния неопределённости»: сервер имеет право использовать её, если не желает раскрывать причины ошибки. После получения ошибки 404, можно сделать повторный запрос, и он вполне может отработать успешно. Для индикации персистентной ошибки «ресурс не найден» используется отдельный статус 410 Gone.

Более интересный вопрос — а что всё-таки клиент может (или должен) сделать, получив такую ошибку. Как мы указывали в главе «Разграничение областей ответственности», если ошибка может быть исправлена программно, необходимо в машиночитаемом виде индицировать это клиенту; если ошибка не может быть исправлена, необходимо включить человекочитаемые сообщения для пользователя (даже просто «попробуйте начать сначала / перезагрузить приложение» лучше с точки зрения UX, чем «неизвестная ошибка») и для разработчика, который будет разбираться с проблемой.

С восстановимыми ошибками в HTTP, к сожалению, ситуация достаточно сложная. С одной стороны, протокол включает в себя множество специальных кодов, которые индицируют проблемы с использованием самого протокола — такие как 405 Method Not Allowed (данный глагол неприменим к указанному ресурсу), 406 Not Acceptable (сервер не может вернуть ответ согласно Accept-заголовкам запроса), 411 Length Required, 414 URI Too Long и так далее. Код клиента может обработать данные ошибки и даже, возможно, предпринять какие-то действия по их устранению (например, добавить заголовок Content-Length в запрос после получения ошибки 411), но все они очень плохо применимы к ошибкам в бизнес-логике. Например, мы можем вернуть 429 Too Many Requests при превышении лимитов запросов, но у нас нет никакого стандартного способа указать, какой именно лимит был превышен.

Частично проблему отсутствия стандартных подходов к возврату ошибок компенсируют использованием различных близких по смыслу статус-кодов для индикации разных состояний (либо и вовсе выбор произвольного кода ошибки и придания ему нового смысла в рамках конкретного API). В частности, сегодня де-факто стандартом является возврат кода 401 Unauthorized при отсутствии заголовков авторизации или невалидном токене (получение этого кода, таким образом, является сигналом для приложения предложить пользователю залогиниться в системе), что противоречит стандарту (который требует при возврате 401 обязательно указать заголовок WWW-Authenticate с описанием способа аутентификации пользователя; нам неизвестны реальные API, которые выполняют это требованием).

Однако таких кодов, которые могут отражать нюансы одной и той же проблемы, в стандарте очень мало. Фактически, мы приходим к тому, что множество различных ошибок в логике приложения приходится возвращать под очень небольшим набором статус-кодов:

  • 400 Bad Request для всех ошибок валидации запроса (некоторые пуристы утверждают, что, вообще говоря, 400 соответствует нарушению формата запроса — невалидному JSON, например — а для логических ошибок следует использовать код 422 Unprocessable Content; в постановке задачи это мало что меняет);

  • 403 Forbidden для любых проблем, связанных с авторизацией действий клиента;

  • 404 Not Found в случае, если какие-то из указанных в запросе сущностей не найдены либо раскрытие причин ошибки нежелательно;

  • 409 Conflict при нарушении целостности данных;

  • 410 Gone если ресурс был удалён;

  • 429 Too Many Requests при превышении лимитов.

Разработчики стандарта HTTP об этой проблеме вполне осведомлены, и отдельно отмечают, что для решения бизнес-сценариев необходимо передавать в метаданных либо теле ответа дополнительные данные для описания возникшей ситуации («the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition»), что (как и введение новых специальных кодов ошибок) противоречит самой идее унифицированного машиночитаемого формата ошибок. (Отметим, что отсутствие стандартов описания ошибок в бизнес-логике — одна из основных причин, по которым мы считаем разработку REST API как его описал Филдинг в манифесте 2008 года невозможной; клиент должен обладать априорным знанием о том, как работать с метаинформацией об ошибке, иначе он сможет восстанавливать своё состояние после ошибки только перезагрузкой.)

Дополнительно, у проблемы есть и третье измерение в виде серверного ПО мониторинга состояния системы, которое часто полагается на статус-коды ответов при построении графиков и уведомлений. Между тем, ошибки, скрывающиеся под одним статус кодом — например ввод неправильного пароля и истёкший срок жизни токена — могут быть очень разными по смыслу; повышенный фон первой ошибки может говорить о потенциальной попытке взлома путём перебора паролей, а второй — о потенциальных ошибках в новой версии приложения, которая может неверно кэшировать токены авторизации.

Всё это естественным образом подводит нас к следующему выводу: если мы хотим использовать ошибки для диагностики и (возможно) восстановления состояния клиента, нам необходимо добавить машиночитаемую метаинформацию о подвиде ошибки и, возможно, тело ошибки с указанием подробной информации о проблемах — например, как мы предлагали в главе «Описание конечных интерфейсов»:

POST /v1/coffee-machines/search HTTP/1.1

{
  "recipes": ["lngo"],
  "position": {
    "latitude": 110,
    "longitude": 55
  }
}
→
HTTP/1.1 400 Bad Request
X-OurCoffeeAPI-Error-Kind:⮠
  wrong_parameter_value

{
  "reason": "wrong_parameter_value",
  "localized_message":
    "Что-то пошло не так.⮠
    Обратитесь к разработчику приложения.",
  "details": {
    "checks_failed": [{
      "field": "recipe",
      "error_type": "wrong_value",
      "message":
        "Value 'lngo' unknown.⮠
        Did you mean 'lungo'?"
    }, {
      "field": "position.latitude",
      "error_type": "constraint_violation",
      "constraints": {
        "min": -90,
        "max": 90
      },
      "message":
        "'position.latitude' value⮠
        must fall within⮠
        the [-90, 90] interval"
    }]
  }
}

Также напомним, что любые неизвестные 4xx-статус-коды клиент должен трактовать как ошибку 400 Bad Request, следовательно, формат (мета)данных ошибки 400 должен быть максимально общим.

Серверные ошибки

Ошибки 5xx индицируют, что клиент, со своей стороны, выполнил запрос правильно, и проблема заключается в сервере. Для клиента, по большому счёту, важно только то, имеет ли смысл повторять запрос и, если да, то через какое время. Если учесть, что в любых публично доступных API причины серверных ошибок, как правило, не раскрывают — в абсолютном большинстве кодов 500 Internal Server Error и 503 Service Unavailable достаточно для индикации серверных ошибок (второй код указывает, что отказ в обслуживании имеет разовый характер и есть смысл автоматически повторить запрос), или можно вовсе ограничиться одним из них с опциональным заголовком Retry-After.

Для внутренних систем, вообще говоря, такое рассуждение неверно. Для построения правильных мониторингов и системы оповещений необходимо, чтобы серверные ошибки, точно так же, как и клиентские, содержали подтип ошибки в машиночитаемом виде. Здесь по-прежнему применимы те же подходы — использование широкой номенклатуры кодов и/или передача типа ошибки заголовком — однако эта информация должна быть вырезана гейтвеем на границе внешней и внутренней систем, и заменена на общую информацию для разработчика и для конечного пользователя системы с описанием действий, которые необходимо выполнить при получении ошибки.

POST /v1/orders/?user_id=<user id> HTTP/1.1
If-Match: <ревизия>

{ parameters }
→
// Ответ, полученный гейтвеем
// от сервиса обработки заказов,
// метаданные которого будут
// использованы для мониторинга
HTTP/1.1 500 Internal Server Error
// Тип ошибки: получен таймаут от БД
X-OurCoffeAPI-Error-Kind: db_timeout
{ /* Дополнительные данные, например,
     какой хост ответил таймаутом */ }
// Ответ, передаваемый клиенту.
// Детали серверной ошибки удалены
// и заменены на инструкцию клиенту.
// Поскольку гейтвей не знает, был
// ли в действительности сделан заказ,
// клиенту рекомендуется попробовать
// повторить запрос и/или попытаться
// получить актуальное состояние
HTTP/1.1 500 Internal Server Error
Retry-After: 5

{ 
  "reason": "internal_server_error",
  "localized_message": "Не удалось⮠
    получить ответ от сервера.⮠
    Попробуйте повторить операцию
    или обновить страницу.",
  "details": {
    "can_be_retried": true,
    "is_operation_failed": "unknown"
  }
}

Вот здесь мы, однако, вступаем на очень скользкую территорию. Современная практика реализации HTTP-клиентов такова, что безусловно повторяются только немодифицирующие (GET, HEAD, OPTIONS) запросы. В случае модифицирующих запросов разработчик должен написать код, который повторит запрос — и для этого разработчику нужно очень внимательно прочитать документацию к API, чтобы убедиться, что это поведение допустимо и не приведёт к побочным эффектам.

Теоретически идемпотентные методы PUT и DELETE можно вызывать повторно. Практически, однако, ввиду того, что многие разработчики упускают требование идемпотентности этих методов, фреймворки работы с HTTP API по умолчанию перезапросов модифицирующих методов, как правило, не делают, но некоторую выгоду из следования стандарту мы всё же можем извлечь — по крайней мере, сама сигнатура индицирует, что запрос можно повторять.

Что касается более сложных ситуаций, когда мы хотим указать разработчику, что он может безопасно повторить потенциально неидемпотентную операцию, то мы могли бы предложить формат описания доступных действий в теле ошибки… но практически никто не ожидает найти такое описание в самой ошибке. Возможно, потому, что с ошибками 5xx, в отличие от 4xx, программисты практически не сталкиваются при написании клиентского кода, и мало какие тестовые среды позволяют такие ошибки эмулировать. Так или иначе, описывать необходимые действия при получении серверной ошибки вам придётся в документации. (Имейте в виду, что эти инструкции с большой долей вероятности будут проигнорированы. Таков путь.)

Организация системы ошибок в HTTP API на практике

Как понятно из вышесказанного, фактически есть три способа работать с ошибками HTTP API:

  1. Расширительно трактовать номенклатуру статус-кодов и использовать новый код каждый раз, когда требуется индицировать новый вид ошибки. (Автор этой книги неоднократно встречал ситуации, когда при разработке API просто выбирался «похоже выглядящий» статус безо всякой оглядки на его описание в стандарте.)

  2. Полностью отказаться от использования статус-кодов и вкладывать описание ошибки в тело и/или метаданные ответа с кодом 200. Этим путём идут почти все RPC-фреймворки.

    • 2а. Вариантом этой стратегии можно считать использование всего двух статус-кодов ошибок (400 для любой клиентской ошибки, 500 для любой серверной), опционально трёх (те же плюс 404 для статуса неопределённости).

  3. Применить смешанный подход, то есть использовать статус-код согласно его семантике для индикации рода ошибки и вложенные (мета)данные в специально разработанном формате для детализации (подобно фрагментам кода, предложенным нами в настоящей главе).

Как нетрудно заметить, считать соответствующим стандарту можно только подход (3). Будем честны и скажем, что выгоды следования ему, особенно по сравнению с вариантом (2а), не очень велики и состоят в основном в чуть лучшей читабельности логов и большей прозрачности для промежуточных прокси.

Глава 40. Заключительные положения и общие рекомендации 

Подведём итог описанному в предыдущих главах. Чтобы разработать качественный HTTP API, необходимо:

  1. Описать happy path, т.е. составить диаграмму вызовов для стандартного цикла работы клиентского приложения.

  2. Определить каждый вызов как операцию над некоторым ресурсом и, таким образом, составить номенклатуру URL и применимых методов.

  3. Понять, какие ошибки возможны при выполнении операций и каким образом клиент должен восстанавливаться из какого состояния.

  4. Решить, какая функциональность будет передана на уровень протокола HTTP [какие стандартные возможности протокола будут использованы в сопряжении с какими инструментами разработки] и в каком объёме.

  5. Опираясь на решения 1-4, разработать конкретную спецификацию.

  6. Проверить себя: пройти по пунктам 1-3, написать псевдокод бизнес-логики приложения согласно разработанной спецификации, и оценить, насколько удобным, понятным и читабельным оказался результирующий API.

Позволим себе так же дать несколько советов по code style:

  1. Не различайте пути с / на конце и без него и примите какую-то рекомендацию по умолчанию (мы рекомендуем все пути заканчивать на / — по простой причине, это позволяет разумно описать обращение к корню домена как ГЛАГОЛ /). Если вы решили запретить один из вариантов (скажем, пути без слэша в конце), при обращении по второму варианту должен быть или редирект или однозначно читаемая ошибка.

  2. Включайте в ответы стандартные заголовки — Date, Content-Type, Content-Encoding, Content-Length, Cache-Control, Retry-After — и вообще старайтесь не полагаться на то, что клиент правильно догадывается о параметрах протокола по умолчанию.

  3. Поддержите метод OPTIONS и протокол CORS на случай, если ваш API захотят использовать из браузеров.

  4. Определитесь с правилами выбора кейсинга параметров (и преобразований кейсинга при перемещении параметра между различными частями запроса) и придерживайтесь их.

  5. Всегда оставляйте себе возможность обратно-совместимого расширения операции API. В частности, всегда возвращайте корневой JSON-объект в ответах эндпойтов — потому что приписать новые поля к объекту вы можете, а к массивам и примитивам — нет.

    • Отметим также, что пустая строка не является валидным JSON, поэтому корректнее возвращать пустой объект {} там, где ответа не подразумевается (или статус 204 No Content с пустым телом, но тогда эндпойнт нельзя будет расширить в будущем).

  6. Для всех GET-запросов указывайте политику кэширования (иначе всегда есть шанс, что клиент или промежуточный агент придумает её за вас).

  7. Не эксплуатируйте известные возможности оперировать запросами в нарушение стандарта и не изобретайте свои решения для «серых зон» протокола. В частности:

    • не размещайте модифицирующие операции за методом GET и неидемпотентные операции за PUT / DELETE;

    • соблюдайте симметрию GET / PUT / DELETE методов;

    • не позволяйте GET / HEAD / DELETE-запросам иметь тело, не возвращайте тело в ответе метода HEAD или совместно со статус-кодом 204 No Content;

    • не придумывайте свой стандарт для передачи массивов и вложенных объектов в query — лучше воспользоваться HTTP-глаголом, позволяющим запросу иметь тело, или, в крайнем случае, передать параметры в виде Base64-кодированного JSON-поля;

    • не размещайте в пути и домене URL параметры, по формату требующие эскейпинга (т.е. могущие содержать символы, отличные от цифр и букв латинского алфавита); для этой цели лучше воспользоваться query-параметрами или телом запроса.

  8. Ознакомьтесь хотя бы с основными видами уязвимостей в типичных имплементациях HTTP API, которыми могут воспользоваться злоумышленники:

    • CSFR

    • SSRF

    • HTTP Response Splitting

    • Unvalidated Redirects and Forwards

    и заложите защиту от этих векторов атак на уровне вашего серверного ПО. Организация OWASP предоставляет хороший обзор лучших security-практик для HTTP API.

В заключение хотелось бы сказать следующее: HTTP API — это способ организовать ваше API так, чтобы полагаться на понимание семантики операций как разнообразным программным обеспечением, от клиентских фреймворков до серверных гейтвеев, так и разработчиком, который читает спецификацию. В этом смысле экосистема HTTP предоставляет пожалуй что наиболее широкий (и в плане глубины, и в плане распространённости) по сравнению с другими технологиями словарь для описания самых разнообразных ситуаций, возникающих во время работы клиент-серверных приложений. Разумеется, эта технология не лишена своих недостатков, но для разработчика публичного API она является выбором по умолчанию — на сегодняшний день скорее надо обосновывать отказ от HTTP API чем выбор в его пользу.

Your question is good, but I do believe it to be based on opinions. The choice of the appropriate code should be made according to the current RFC. However, like any other standard, the RFC is not always clear and can be interpreted in a variety of ways.

Here are my thoughts on the answers already given and my opinion.

1. Where and where should I look for sources for questions like this?

First of all, the RFC regarding this and what is in vogue at the moment is the 7231 < a>. If you are familiar with English, I suggest you read it to create your own opinions as well.

2. About not using 200 code

Although some web frameworks return 200 in the case of requests with invalid data, I do not believe that this should be the proper code.

According to item 6.3 of 7231, 2xx codes indicate that the customer request has been received, understood and accepted.

So if the purpose of a POST request is to create a new object on the server, and this is not done due to invalid data, I do not think that the code 200 should be returned saying that the request was a success , but rather a code indicating that an error occurred in the processing of sent data.

3. About using the 400 code

If we think that the data sent is also part of the request, if it is invalid and therefore wrong, it is not fair to return a code 400, which indicates a bad request.

Setting the POST method

Looking at the definition of the POST method in the RFC strengthens this idea. According to item 4.3.3, a POST request is requesting that a given resource (or resource ) process the data present in the request according to the semantics of the resource. So, if you send a data that has no meaning to the server, the request will not be understood and should not be processed.

Definition of class 4xx and code 400

Another argument to strengthen the use of the 400 code is the definition of the 4xx class and its own definition:

Class 4xx has codes for when the client makes a mistake. If you understand that the client is responsible for sending valid data (and that validation on the server is done by security measure) 4xx seems to be the appropriate class. It is important to note that class 4xx, according to the RFC, should always return an explanation of the error to the client.

The code 400, in turn, indicates that the server can not, is not able or will not simply process the request by error of the client (the error of sending data that does not have meaning according to the requested resource).

It is important to remember that the RFC does not list the errors that a client can commit, listing only a few examples (syntax error is one of them).

4. Soon …

In conclusion, the client is responsible for sending data that makes sense to the server, and if it does not, this should be considered a client error. Therefore, I suggest use code 400 and, as provided in the RFC, send a message explaining the error, saying that the data is not valid.

Bonus: Methods you definitely should not use

418: is not a code present in the current RFC and has no semantic value for data validation.

405: Should be used only when the request method is not accepted by the server and not the data itself.

    

When building APIs for the first time, it is important to understand error status codes and how they impact the overall performance of the API. Error status codes are essential for ensuring that the API is functioning correctly, communicating errors and warnings to the user or system, and providing a seamless experience.

It is important to understand the different types of error status codes, what they mean, and how to interpret them so that your API will function properly.

This blog post will explore the various API error status codes and how to interpret them when building APIs for the first time.

It will provide a comprehensive discussion on the different types of error codes and the best practices for handling them, as well as provide a few tips to help make your API building experience as smooth as possible.

  • What are API error Codes?
  • Client-side status code

    1. 404 — Not Found
    2. 401 — Unauthorized
    3. 403 — Forbidden
    4. 400 — Bad Request
    5. 429 — Too Many Requests
  • Server-side status code

    1. 500 — Internal Server Error
    2. 502 — Bad Gateway
    3. 503 — Service Unavailable
    4. 504 — Gateway Timeout
    5. 501 — Not Implemented
  • Best practices for handling API Error codes

What are API error Codes?

API error codes are standardized status codes that are returned by an API (Application Programming Interface) in response to a client’s request. These codes are used to indicate whether the requested operation was successful or not, and if not, to provide information on the type of error that occurred.

API error codes are typically three-digit numbers, with the first digit indicating the general category of the error, and the remaining two digits specifying the particular error within that category. For example, a 404 error code is a common error that indicates the requested resource was not found on the server.

API Error Status CodesAPI Error Codes

API Error Codes

By providing standardized error codes, APIs can communicate more effectively with clients and developers, and allow them to quickly diagnose and address any issues that arise during the use of the API.

For example, Suppose a client sends a request to an API to retrieve information about a specific resource, such as a user profile, but the API is unable to find that resource. In this case, the API may return a 404 error code, with a message indicating that the requested resource was not found.

The 404 error code is a standardized HTTP status code, which indicates that the server was unable to find the requested resource. The first digit «4» indicates that the error falls under the category of client errors, meaning that the error was caused by an issue with the client’s request, rather than an issue with the server. The remaining two digits «04» specify the specific error within that category, in this case, «not found».

The client can then use this information to understand that the requested resource was not found, and take appropriate action, such as displaying an error message to the user or retrying the request with different parameters.

There are two types of error status codes when you build an API for the first time.

  1. Client-side Status Code
  2. Server-side Status Code

Client-side Status Code

Client-side status codes are HTTP response codes that are generated by a client’s web browser in response to a server’s attempt to fulfill the client’s request. These codes are used to communicate information about the status of the request to the client, and they can help the client to take appropriate action based on the response.

The 4XX series of status codes often refers to client-side failures, though they can also result from modifications to the API. The top 5 client-side status error codes are listed below, along with explanations of how to fix them.

There are 5 common client-side status codes when you build an API:

1. 400 — Bad Request

The 400 Bad Request error is an HTTP response status code that indicates that the server cannot understand the request sent by the client because it was malformed or incomplete. This means that the server is unable to process the request and return the desired response.

Ways to fix the 400 — Bad Request error

  1. Check the URL: Make sure the URL you’re trying to access is correct and complete.
  2. Clear your cache and cookies: Clearing your browser’s cache and cookies can sometimes help fix the 400 error.
  3. Check your request syntax: Double-check that your request syntax is correct, including all necessary headers and parameters.
  4. Check for outdated software: Make sure that your web browser, operating system, and other software are up-to-date.
  5. Disable browser extensions: Try disabling any browser extensions that may be interfering with your web requests.
  6. Contact the website owner: If you’re trying to access a specific website, you can try contacting the website owner or technical support team for assistance.
  7. Try a different browser or device: If you’re still having trouble after trying the above steps, you can try accessing the website from a different browser or device.

The client request has not been fulfilled because it does not contain proper authentication credentials for the requested resource, as indicated by the HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code.

Because the client request does not contain proper authentication credentials for the requested resource, the HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been fulfilled.

This error indicates that the website or web application was unable to authenticate the request that was made. Fortunately, this problem may typically be quickly fixed.

Ways to fix 401 — Unauthorized Error

  • Verify that you are using a valid user ID and password to log in.
  • It may be worthwhile to momentarily disable password security for the troublesome area of your website if you’re a webmaster trying to fix the 401 issue.
  • It may be worthwhile to momentarily disable password security for the troublesome area of your website if you’re a webmaster trying to fix the 401 issue. Clear it!

3. 403 — Forbidden

Although the server recognizes the request, it will not grant access, as shown by the HTTP response status code 403 Forbidden. For the 403 Forbidden status code, re-authenticating has no effect, even though this status is comparable to 401. Such as insufficient privileges to a resource, the access is connected to the application logic.

Simply put, it indicates that the website’s content you’re seeking to access is being banned for a specified reason. Although the cause could be something in your power, the content owner or server is more likely to be to blame.

A request that the server cannot accept results in a 403 Forbidden error. This frequently happens because of firewall rules that categorically forbid making this particular request, but other settings, including permissions, may also restrict access based on user privileges.

Ways to fix 403 — Forbidden error

  • If you’ve made it this far and none of the previous fixes have worked, there’s a good possibility that the issue is the result of a malfunctioning or incompatible plugin. Try disabling plugins.
  • Verify the name of the homepage on your website; it should be index.html or index.php. The first and easiest is to change the homepage’s name to index.html or index.php.

4. 404 — Not Found

A website user will be informed if a requested page is unavailable with the status code 404. The Hypertext Transfer Protocol response codes on the web include 404 and various response status codes. The 404 error number indicates that a client’s requested webpage was not found by the server.

These happen when a page cannot be located. If the URL is typed incorrectly or the page has been erased, this may occur. These 400 errors show that the request cannot be processed by the server. This may occur if there is a coding issue or if the website is unavailable for maintenance.

Ways to fix 404 — Page Not Found Error

  • Open a new window and try to close the current one.
  • erase the cache. Delete the history and data from your browser.
  • To be sure you typed in the proper website address in the search bar, double-check the URL.
  • Make sure your website doesn’t include any broken links.

5. 429 — Too Many Requests

When a user sends too many requests in a short period, the HTTP 429 Too Many Requests response status code shows this («rate limiting»). This answer may have a Retry-After header stating how long it should be before a fresh request is made.

The lack of resources to handle so many concurrent requests is the main reason behind 429 errors. If this error, for instance, appears on a hosting server, it may indicate that the package you are using has a cap on the number of requests you are permitted to submit.

Ways to fix 429 — Too many requests error

  • The next time you come, the browser can load the website more quickly thanks to cached data. But, as this data builds up, the 429 error may appear. Thus, the first step is to empty the cache on your browser.
  • Conflicts may also result from WordPress themes with poor coding. Switching to a default WordPress theme is the simplest method to address this problem.

Server-side Status Code

Server-side status codes are HTTP response codes that are generated by a web server in response to a client’s request for a resource. These status codes provide information about the status of the server’s attempt to fulfill the request, and they help to ensure that the client and server can communicate effectively.

The 5XX group of status codes typically returns in response to a server error, but if the server misses an invalid API call that ought to produce a 4XX answer, it may also return a 5XX error.

1. 500 — Internal Server Error

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code denotes that the request could not be processed by the server due to an unexpected condition. This error message is an all-purpose «catch-all» message.

Since the 500 Internal Server Error is a server-side issue, it is most likely not your computer or internet connection that is at fault, but rather the server hosting the website. Although unlikely, there could be a problem on your end, in which case you can try the following: Refresh the website.

When a server-side issue prohibits Apache from handling a request and providing a suitable response, Apache returns a 500 Internal Server Error. This may be the result of several factors, including flawed code, insufficient file permissions, and missing files mentioned in the code.

Ways to fix 500 — Internal Server Error:

  • Attempt refreshing the page. The website may return immediately if the host or server is just overloaded.
  • Themes and plugins from unofficial sources might easily result in 500 internal server issues. Deactivate them.

2. 501 — Not Implemented

The server does not support the functionality required to complete the request if the HyperText Transfer Protocol (HTTP) 501 Not Implemented server error response code is returned. The Retry-After header, which notifies the requester when to check back to see if the functionality is supported by then, may also be sent by this status.

You can’t fix the problem yourself because it’s a server-side error; it needs to be fixed by the server and website management.

An HTTP error message, also known as an HTTP status code, is returned by a browser when it accesses a page and discovers something that doesn’t operate properly. A problem on the server is indicated if the message’s code begins with a 5.

This indicates that anything on the server’s end of the website is malfunctioning and preventing a full page load. The root causes of this problem, however, can vary.

Ways to fix 501 — Not Implemented Error:

  • Malware or viruses on the computer could be the cause of Error 501. Thus, it’s crucial to do a comprehensive scan of your antivirus software and maintain it updated.
  • Checking the server’s log files to see if any error messages can aid with the problem can be another idea for resolving it.

3. 502 — Bad Gateway

A 502 bad gateway message denotes that a server received a faulty answer from another server. In essence, you have established a connection with some sort of temporary device (such as an edge server) that should fetch all the information required to load the page.

The notice identifies the issue as anything with that process that went wrong. It denotes a server issue rather than one with your device, router, or internet connection. There’s a good chance that other website visitors are having the same issue.

Ways to fix 502 — Bad Gateway Error

  • Deciding to re-route your internet traffic over a virtual private network (VPN) can assist you to figure out whether the connection to the site is having problems because of your ISP or something else.
  • Clearing the browser’s cache might help if refreshing the browser a few times doesn’t work.
  • Check the web server logs from the time the error occurred.

4. 503 — Service Unavailable

An HTTP response status code of 503 Service Unavailable indicates that although your web server is operational, it is now unable to handle a request. It’s challenging to determine the precise cause of the problem because the error message is only a general one.

You are not at fault because a 503 error on the HTTP protocol usually signifies that the server is having problems. But, you may troubleshoot and resolve the issue by following a few straightforward actions. When you get a 503 service unavailable error message, you could be left scratching your head and wondering what went wrong.

Ways to 503 — Service Unavailable Error:

  • A server employs Memory, CPU, I/O, entry processes, and website inodes as resources. You can determine whether the problem is connected to resource limitations by looking at these metrics.
  • Several web hosting typically gives their users automatic upgrades. You have the opportunity to change the server configuration settings and turn off automatic updates.

5. 504 — Gateway Timeout

The 504 «Gateway Timeout» Error denotes that the browser attempted to send an HTTP request to the server but was unable to do so because it did not receive a timely response from another server. You may usually fix it by refreshing the website.

A 504 Gateway Timeout Error denotes that your web server did not immediately receive a response from an upstream server when it attempted to load one of your web pages. Simply said, the communication between your web servers isn’t happening swiftly enough.

Ways to fix 504 — Gateway Timeout Error:

  • Try opening the WordPress website in incognito mode and using a different browser.
  • An alternative computer, network connection, or mobile device might be able to load the page. To determine whether the issue is with the hardware or the internet connection, you may also try restarting the network devices.

Discover the secrets of HTTP status codes with our Complete Guide! Learn how to use them effectively to communicate with clients and servers, and how to handle errors gracefully.

Best practices for handling API Error Codes

  1. Use standardized error codes: Use well-defined error status codes consistent with industry standards and HTTP specifications. This can make it easier for clients to understand and handle errors.
  2. Provide informative error messages: Include informative and precise error messages and error codes to help clients understand the reason for the error and what action they can take to resolve it.
  3. Be consistent: Ensure consistency in the format and content of error messages and error status codes across all API endpoints to avoid confusion and simplify client error handling.
  4. Use appropriate HTTP methods: Use appropriate HTTP methods to indicate the nature of the request and the desired action. For example, use GET for retrieving data and POST for creating new resources.
  5. Implement retries: Allow clients to retry failed requests after a specified interval to reduce the impact of temporary network or server issues.
  6. Log errors: Log all API errors, including error codes, error messages, and any relevant details, to help diagnose and troubleshoot issues.
  7. Use versioning: Use versioning to indicate API changes and allow clients to migrate to new versions at their own pace without disrupting existing applications.

Here’s an example of how to handle API errors in a Node.js application using the Express framework:

const express = require('express');
const app = express();

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  if (!isValidUserId(userId)) {
    const error = new Error('Invalid user ID');
    error.status = 400; // Set the HTTP status code
    return next(error);
  }
  // Continue with the normal request handling
  // ...
});

// Error handler middleware
app.use((err, req, res, next) => {
  const statusCode = err.status || 500; // Default to 500 if status code not set
  res.status(statusCode).json({
    message: err.message
  });
});

// Helper function to validate user IDs
function isValidUserId(id) {
  // Check if ID is a non-empty string of digits
  return /^\d+$/.test(id);
}

In this example, the API endpoint /users/:id accepts a request to retrieve a user’s information based on their ID. The isValidUserId function is used to validate the user ID, and if it is found to be invalid, an error is thrown with a message of «Invalid user ID» and a status code of 400. The error is then passed to the error handler middleware using the next function, which sets the appropriate status code and sends a JSON response with the error message.

The error handler middleware is a catch-all middleware that handles any errors that occur in the application. It extracts the status code and error message from the error object and sends a JSON response to the client with that information.

By following this pattern, you can ensure that any errors that occur during the handling of an API request are properly handled and communicated to the client in a consistent and informative manner.

Conclusion

Any issue that prevents access to the website should be resolved as quickly as possible. This is because while your page is down, your visitors are unable to access your material, which is bad for your business. After all, you could lose both the visit and a potential client.

The detrimental effects of unavailability on the SEO strategy are one of the key issues they create. This is due to Google periodically crawling the website’s pages for indexing. Hence, it will produce an error message if it tries to access the website and discovers that it is not available.

Refreshing the page and clearing the cache are two simple things that provide reliable solutions for any type of error. Hence, take into account the potential reasons for the problem and the suggested fixes to your website.


Atatus API Monitoring and Observability

Atatus provides Powerful API Observability to help you debug and prevent API issues. It monitors the consumer experience and is notified when abnormalities or issues arise. You can deeply understand who is using your APIs, how they are used, and the payloads they are sending.

Atatus’s user-centric API observability tracks how your actual customers experience your APIs and applications. Customers may easily get metrics on their quota usage, SLAs, and more.

It monitors the functionality, availability, and performance data of your internal, external, and third-party APIs to see how your actual users interact with the API in your application. It also validates rest APIs and keeps track of metrics like latency, response time, and other performance indicators to ensure your application runs smoothly.

Try your 14-day free trial of Atatus!

Справочник ошибок и ответов API

При выполнении некорректного запроса к системе наше API может вернуть код ошибки, в случае же верного запроса, API вернёт ответ. Вы, конечно, уже обрабатывали ответ сервера в ходе отладки своих виджетов или написании скриптов, взаимодействующих с нашей системой. Для Вашего удобства, мы решили систематизировать все возможные ответы и ошибки, отдаваемые нашей системой и разместить их на отдельной странице. Надеемся это облегчит и ускорит интеграцию Ваших проектов с amoCRM.

Ошибки при валидации данных

Если переданные данные не совпадают с теми, что доступны для сущности, запрос вернет HTTP-код 400 Bad Request и массив с параметрами, которые не подошли под условия.

Пример ошибки валидации данных


{
    "validation-errors": [
        {
            "request_id": "0",
            "errors": [
                {
                    "code": "NotSupportedChoice",
                    "path": "custom_fields_values.0.field_id",
                    "detail": "The value you selected is not a valid choice."
                }
            ]
        }
    ],
    "title": "Bad Request",
    "type": "https://httpstatus.es/400",
    "status": 400,
    "detail": "Request validation failed"
}

Ответы при авторизации

Подробнее об авторизации читайте здесь

Код HTTP код Описание
110 401 Unauthorized Общая ошибка авторизации. Неправильный логин или пароль.
111 401 Unauthorized Возникает после нескольких неудачных попыток авторизации. В этом случае нужно авторизоваться в аккаунте через браузер, введя код капчи.
112 401 Unauthorized Возникает, когда пользователь выключен в настройках аккаунта “Пользователи и права” или не состоит в аккаунте.
113 403 Forbidden Доступ к данному аккаунту запрещён с Вашего IP адреса. Возникает, когда в настройках безопасности аккаунта включена фильтрация доступа к API по “белому списку IP адресов”.
101 401 Unauthorized Возникает в случае запроса к несуществующему аккаунту (субдомену).

Ответы при работе с контактами

Подробнее о работе с контактами читайте здесь

Код Описание
202 Добавление контактов: нет прав
203 Добавление контактов: системная ошибка при работе с дополнительными полями
205 Добавление контактов: контакт не создан
212 Обновление контактов: контакт не обновлён
219 Список контактов: ошибка поиска, повторите запрос позднее
330 Добавление/Обновление контактов: количество привязанных сделок слишком большое

Ответы при работе со сделками

Подробнее о работе со сделками читайте здесь

Код Описание
330 Добавление/Обновление сделок: количество привязанных контактов слишком большое

Ответы при работе с событиями

Подробнее о работе с событиями читайте здесь

Код Описание
244 Добавление событий: недостаточно прав для добавления события
225 Обновление событий: события не найдены

Ответы при работе с задачами

Подробнее о работе с задачами читайте здесь

Код Описание
231 Обновление задач: задачи не найдены
233 Добавление событий: по данному ID элемента не найдены некоторые контакты
234 Добавление событий: по данному ID элемента не найдены некоторые сделки
235 Добавление задач: не указан тип элемента
236 Добавление задач: по данному ID элемента не найдены некоторые контакты
237 Добавление задач: по данному ID элемента не найдены некоторые сделки
244 Добавление сделок: нет прав.

Ответы при работе со списками

Подробнее о работе со списками читайте здесь

Код Описание
244 Добавление/Обновление/Удаление каталогов: нет прав.
281 Каталог не удален: внутренняя ошибка
282 Каталог не найден в аккаунте.

Ответы при работе с элементами каталога

Подробнее о работе с элементами каталога читайте здесь

Код Описание
203 Добавление/Обновление элементов каталога: системная ошибка при работе с дополнительными полями
204 Добавление/Обновление элементов каталога: дополнительное поле не найдено
244 Добавление/Обновление/Удаление элементов каталога: нет прав.
280 Добавление элементов каталога: элемент создан.
282 Элемент не найден в аккаунте.

Ответы при работе с покупателями

Подробнее о работе с покупателями читайте здесь

Код Описание
288 Недостаточно прав. Доступ запрещен.
402 Необходимо оплатить функционал
425 Функционал недоступен
426 Функционал выключен

Другие ответы

Ошибки и ответы, не относящиеся к какому-либо конкретному разделу

Код Описание Примечание
400 Неверная структура массива передаваемых данных, либо не верные идентификаторы кастомных полей  
422 Входящие данные не мог быть обработаны.  
405 Запрашиваемый HTTP-метод не поддерживается  
402 Подписка закончилась Вместе с этим ответом отдаётся HTTP код №402 “Payment Required”
403 Аккаунт заблокирован, за неоднократное превышение количества запросов в секунду Вместе с этим ответом отдаётся HTTP код №403
429 Превышено допустимое количество запросов в секунду Вместе с этим ответом отдаётся HTTP код №429
2002 По вашему запросу ничего не найдено Вместе с этим ответом отдаётся HTTP код №204 “No Content”

Понравилась статья? Поделить с друзьями:
  • Api ошибка 403
  • App module exe системная ошибка
  • App module exe ошибка приложения
  • Api ошибка 200
  • App installation failed with error message ошибка 0x80073d02