Rest api статусы ошибок

REST API использует строку состояния в HTTP ответе (статус ответа), чтобы информировать Клиентов о результате запроса.

Вообще HTTP определяет 40 стандартных кодов состояния (статусов ответа), которые делятся на пять категорий. Ниже выделены только те коды состояния, которые часто используются в REST API.

Категория Описание
1xx: Информация В этот класс содержит заголовки информирующие о процессе передачи. Это обычно предварительный ответ, состоящий только из Status-Line и опциональных заголовков, и завершается пустой строкой. Нет обязательных заголовков. Серверы НЕ ДОЛЖНЫ посылать 1xx ответы HTTP/1.0 клиентам.
2xx: Успех Этот класс кодов состояния указывает, что запрос клиента был успешно получен, понят, и принят.
3xx: Перенаправление Коды этого класса сообщают клиенту, что для успешного выполнения операции необходимо сделать другой запрос, как правило, по другому URI. Из данного класса пять кодов 301, 302, 303, 305 и 307 относятся непосредственно к перенаправлениям.
4xx: Ошибка клиента Класс кодов 4xx предназначен для указания ошибок со стороны клиента.
5xx: Ошибка сервера Коды ответов, начинающиеся с «5» указывают на случаи, когда сервер знает, что произошла ошибка или он не может обработать запрос.

Коды состояний в REST

Звездочкой * помечены популярные (часто используемые) коды ответов.

200 * (OK)

Запрос выполнен успешно. Информация, возвращаемая с ответом зависит от метода, используемого в запросе, например при:

  • GET Получен объект, соответствующий запрошенному ресурсу.
  • HEAD Получены поля заголовков, соответствующие запрошенному ресурсу, тело ответа пустое.
  • POST Запрошенное действие выполнено.

201 * (Created — Создано)

REST API отвечает кодом состояния 201 при каждом создании ресурса в коллекции. Также могут быть случаи, когда новый ресурс создается в результате какого-либо действия контроллера, и в этом случае 201 также будет подходящем ответом.

Ссылка (URL) на новый ресурс может быть в теле ответа или в поле заголовка ответа Location.

Сервер должен создать ресурс перед тем как вернуть 201 статус. Если это невозможно сделать сразу, тогда сервер должен ответить кодом 202 (Accepted).

202 (Accepted — Принято)

Ответ 202 обычно используется для действий, которые занимают много времени для обработки и не могут быть выполнены сразу. Это означает, что запрос принят к обработке, но обработка не завершена.

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

Сущность, возвращаемая с этим ответом, должна содержать указание на текущее состояние запроса и указатель на монитор состояния (расположение очереди заданий) или некоторую оценку того, когда пользователь может ожидать выполнения запроса.

203 (Non-Authoritative Information — Неавторитетная информация)

Предоставленная информация взята не из оригинального источника (а, например, из кэша, который мог устареть, или из резервной копии, которая могла потерять актуальность). Этот факт отражен в заголовке ответа и подтверждается этим кодом. Предоставленная информация может совпадать, а может и не совпадать с оригинальными данными.

204 * (No Content — Нет контента)

Код состояния 204 обычно отправляется в ответ на запрос PUT, POST или DELETE, когда REST API отказывается отправлять обратно любое сообщение о состоянии проделанной работы.

API может также отправить 204 статус в ответ на GET запрос, чтобы указать, что запрошенный ресурс существует, но не имеет данных для добавления их в тело ответа.

Ответ 204 не должен содержать тело сообщения и, таким образом, всегда завершается первой пустой строкой после полей заголовка.

205 — (Reset Content — Сброшенное содержимое)

Сервер успешно обработал запрос и обязывает клиента сбросить введенные пользователем данные. В ответе не должно передаваться никаких данных (в теле ответа). Обычно применяется для возврата в начальное состояние формы ввода данных на клиенте.

206 — (Partial Content — Частичное содержимое)

Сервер выполнил часть GET запроса ресурса. Запрос ДОЛЖЕН был содержать поле заголовка Range (секция 14.35), который указывает на желаемый диапазон и МОГ содержать поле заголовка If-Range (секция 14.27), который делает запрос условным.

Запрос ДОЛЖЕН содержать следующие поля заголовка:

  • Либо поле Content-Range (секция 14.16), который показывает диапазон, включённый в этот запрос, либо Content-Type со значением multipart/byteranges, включающими в себя поля Content-Range для каждой части. Если в заголовке запроса есть поле Content-Length, его значение ДОЛЖНО совпадать с фактическим количеством октетов, переданных в теле сообщения.
  • Date
  • ETag и/или Content-Location, если ранее был получен ответ 200 на такой же запрос.
  • Expires, Cache-Control, и/или Vary, если значение поля изменилось с момента отправления последнего такого же запроса

Если ответ 206 — это результат выполнения условного запроса, который использовал строгий кэш-валидатор (подробнее в секции 13.3.3), в ответ НЕ СЛЕДУЕТ включать какие-либо другие заголовки сущности. Если такой ответ — результат выполнения запроса If-Range, который использовал «слабый» валидатор, то ответ НЕ ДОЛЖЕН содержать другие заголовки сущности; это предотвращает несоответствие между закэшированными телами сущностей и обновлёнными заголовками. В противном случае ответ ДОЛЖЕН содержать все заголовки сущностей, которые вернули статус 200 (OK) на тот же запрос.

Кэш НЕ ДОЛЖЕН объединять ответ 206 с другими ранее закэшированными данными, если поле ETag или Last-Modified в точности не совпадают (подробнее в секции 16.5.4)

Кэш, который не поддерживает заголовки Range и Content-Range НЕ ДОЛЖЕН кэшировать ответы 206 (Partial).

300 — (Multiple Choices — Несколько вариантов)

По указанному URI существует несколько вариантов предоставления ресурса по типу MIME, по языку или по другим характеристикам. Сервер передаёт с сообщением список альтернатив, давая возможность сделать выбор клиенту автоматически или пользователю.

Если это не запрос HEAD, ответ ДОЛЖЕН включать объект, содержащий список характеристик и адресов, из которого пользователь или агент пользователя может выбрать один наиболее подходящий. Формат объекта определяется по типу данных приведённых в Content-Type поля заголовка. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего варианта может выполняться автоматически. Однако эта спецификация не определяет никакого стандарта для автоматического выбора.

Если у сервера есть предпочтительный выбор представления, он ДОЛЖЕН включить конкретный URI для этого представления в поле Location; агент пользователя МОЖЕТ использовать заголовок Location для автоматического перенаправления к предложенному ресурсу. Этот запрос может быть закэширован, если явно не было указано иного.

301 (Moved Permanently — Перемещено навсегда)

Код перенаправления. Указывает, что модель ресурсов REST API была сильно изменена и теперь имеет новый URL. Rest API должен указать новый URI в заголовке ответа Location, и все будущие запросы должны быть направлены на указанный URI.

Вы вряд ли будете использовать этот код ответа в своем API, так как вы всегда можете использовать версию API для нового API, сохраняя при этом старый.

302 (Found — Найдено)

Является распространенным способом выполнить перенаправление на другой URL. HTTP-ответ с этим кодом должен дополнительно предоставит URL-адрес куда перенаправлять в поле заголовка Location. Агенту пользователя (например, браузеру) предлагается в ответе с этим кодом сделать второй запрос на новый URL.

Многие браузеры реализовали этот код таким образом, что нарушили стандарт. Они начали изменять Тип исходного запроса, например с POST на GET. Коды состояния 303 и 307 были добавлены для серверов, которые хотят однозначно определить, какая реакция ожидается от клиента.

303 (See Other — Смотрите другое)

Ответ 303 указывает, что ресурс контроллера завершил свою работу, но вместо отправки нежелательного тела ответа он отправляет клиенту URI ресурса. Это может быть URI временного сообщения о состоянии ресурса или URI для уже существующего постоянного ресурса.

Код состояния 303 позволяет REST API указать ссылку на ресурс, не заставляя клиента загружать ответ. Вместо этого клиент может отправить GET запрос на URL указанный в заголовке Location.

Ответ 303 не должен кэшироваться, но ответ на второй (перенаправленный) запрос может быть кэшируемым.

304 * (Not Modified — Не изменен)

Этот код состояния похож на 204 (Нет контента), так как тело ответа должно быть пустым. Ключевое различие состоит в том, что 204 используется, когда нет ничего для отправки в теле, тогда как 304 используется, когда ресурс не был изменен с версии, указанной заголовками запроса If-Modified-Since или If-None-Match.

В таком случае нет необходимости повторно передавать ресурс, так как у клиента все еще есть ранее загруженная копия.

Все это экономит ресурсы клиента и сервера, так как только заголовки должны быть отправлены и приняты, и серверу нет необходимости генерировать контент снова, а клиенту его получать.

305 — (Use Proxy — Используйте прокси)

Доступ к запрошенному ресурсу ДОЛЖЕН быть осуществлен через прокси-сервер, указанный в поле Location. Поле Location предоставляет URI прокси. Ожидается, что получатель повторит этот запрос с помощью прокси. Ответ 305 может генерироваться ТОЛЬКО серверами-источниками.

Заметьте: в спецификации RFC 2068 однозначно не сказано, что ответ 305 предназначен для перенаправления единственного запроса, и что он должен генерироваться только сервером-источником. Упущение этих ограничений вызвало ряд значительных последствий для безопасности.

Многие HTTP клиенты (такие, как Mozilla и Internet Explorer) обрабатывают этот статус некорректно прежде всего из соображений безопасности.

307 (Temporary Redirect — Временный редирект)

Ответ 307 указывает, что rest API не будет обрабатывать запрос клиента. Вместо этого клиент должен повторно отправить запрос на URL, указанный в заголовке Location. Однако в будущих запросах клиент по-прежнему должен использоваться исходный URL.

Rest API может использовать этот код состояния для назначения временного URL запрашиваемому ресурсу.

Если метод запроса не HEAD, тело ответа должно содержать короткую заметку с гиперссылкой на новый URL. Если код 307 был получен в ответ на запрос, отличный от GET или HEAD, Клиент не должен автоматически перенаправлять запрос, если он не может быть подтвержден Клиентом, так как это может изменить условия, при которых был создан запрос.

308 — (Permanent Redirect — Постоянное перенаправление) (experimental)

Нужно повторить запрос на другой адрес без изменения применяемого метода.

Этот и все последующие запросы нужно повторить на другой URI. 307 и 308 (как предложено) Схож в поведении с 302 и 301, но не требуют замены HTTP метода. Таким образом, например, отправку формы на «постоянно перенаправленный» ресурс можно продолжать без проблем.

400 * (Bad Request — Плохой запрос)

Это общий статус ошибки на стороне Клиента. Используется, когда никакой другой код ошибки 4xx не уместен. Ошибки могут быть как неправильный синтаксис запроса, неверные параметры запроса, запросы вводящие в заблуждение или маршрутизатор и т.д.

Клиент не должен повторять точно такой же запрос.

401 * (Unauthorized — Неавторизован)

401 сообщение об ошибке указывает, что клиент пытается работать с закрытым ресурсом без предоставления данных авторизации. Возможно, он предоставил неправильные учетные данные или вообще ничего. Ответ должен включать поле заголовка WWW-Authenticate, содержащего описание проблемы.

Клиент может повторить запрос указав в заголовке подходящее поле авторизации. Если это уже было сделано, то в ответе 401 будет указано, что авторизация для указанных учетных данных не работает. Если в ответе 401 содержится та же проблема, что и в предыдущем ответе, и Клиент уже предпринял хотя бы одну попытку проверки подлинности, то пользователю Клиента следует представить данные полученные в ответе, владельцу сайта, так как они могут помочь в диагностике проблемы.

402 — (Payment Required — Требуется оплата)

Этот код зарезервирован для использования в будущем.

Предполагается использовать в будущем. В настоящий момент не используется. Этот код предусмотрен для платных пользовательских сервисов, а не для хостинговых компаний. Имеется в виду, что эта ошибка не будет выдана хостинговым провайдером в случае просроченной оплаты его услуг. Зарезервирован, начиная с HTTP/1.1.

403 * (Forbidden — Запрещено)

Ошибка 403 указывает, что rest API отказывается выполнять запрос клиента, т.е. Клиент не имеет необходимых разрешений для доступа. Ответ 403 не является случаем, когда нужна авторизация (для ошибки авторизации используется код 401).

Попытка аутентификация не поможет, и повторные запросы не имеют смысла.

404 * (Not Found — Не найдено)

Указывает, что rest API не может сопоставить URL клиента с ресурсом, но этот URL может быть доступен в будущем. Последующие запросы клиента допустимы.

404 не указывает, является ли состояние временным или постоянным. Для указания постоянного состояния используется код 410 (Gone — Пропал). 410 использоваться, если сервер знает, что старый ресурс постоянно недоступен и более не имеет адреса.

405 (Method Not Allowed — Метод не разрешен)

API выдает ошибку 405, когда клиент пытался использовать HTTP метод, который недопустим для ресурса. Например, указан метод PUT, но такого метода у ресурса нет.

Ответ 405 должен включать Заголовок Allow, в котором перечислены поддерживаемые HTTP методы, например, Allow: GET, POST.

406 (Not Acceptable — Неприемлемый)

API не может генерировать предпочитаемые клиентом типы данных, которые указаны в заголовке запроса Accept. Например, запрос клиента на данные в формате application/xml получит ответ 406, если API умеет отдавать данные только в формате application/json.

В таких случаях Клиент должен решить проблему данных у себя и только потом отправлять запросы повторно.

407 — (Proxy Authentication Required — Требуется прокси-аутентификация)

Ответ аналогичен коду 401, за исключением того, что аутентификация производится для прокси-сервера. Механизм аналогичен идентификации на исходном сервере.

Пользователь должен сначала авторизоваться через прокси. Прокси-сервер должен вернуть Proxy-Authenticate заголовок, содержащий запрос ресурса. Клиент может повторить запрос вместе с Proxy-Authenticate заголовком. Появился в HTTP/1.1.

408 — (Request Timeout — Таймаут запроса)

Время ожидания сервером передачи от клиента истекло. Клиент не предоставил запрос за то время, пока сервер был готов его принят. Клиент МОЖЕТ повторить запрос без изменений в любое время.

Например, такая ситуация может возникнуть при загрузке на сервер объёмного файла методом POST или PUT. В какой-то момент передачи источник данных перестал отвечать, например, из-за повреждения компакт-диска или потери связи с другим компьютером в локальной сети. Пока клиент ничего не передаёт, ожидая от него ответа, соединение с сервером держится. Через некоторое время сервер может закрыть соединение со своей стороны, чтобы дать возможность другим клиентам сделать запрос.

409 * (Conflict — Конфликт)

Запрос нельзя обработать из-за конфликта в текущем состоянии ресурса. Этот код разрешается использовать только в тех случаях, когда ожидается, что пользователь может самостоятельно разрешить этот конфликт и повторить запрос. В тело ответа СЛЕДУЕТ включить достаточное количество информации для того, чтобы пользователь смог понять причину конфликта. В идеале ответ должен содержать такую информацию, которая поможет пользователю или его агенту исправить проблему. Однако это не всегда возможно и это не обязательно.

Как правило, конфликты происходят во время PUT-запроса. Например, во время использования версионирования, если сущность, к которой обращаются методом PUT, содержит изменения, конфликтующие с теми, что были сделаны ранее третьей стороной, серверу следует использовать ответ 409, чтобы дать понять пользователю, что этот запрос нельзя завершить. В этом случае в ответной сущности должен содержаться список изменений между двумя версиями в формате, который указан в поле заголовка Content-Type.

410 — (Gone — Исчез)

Такой ответ сервер посылает, если ресурс раньше был по указанному URL, но был удалён и теперь недоступен. Серверу в этом случае неизвестно и местоположение альтернативного документа, например, копии. Если у сервера есть подозрение, что документ в ближайшее время может быть восстановлен, то лучше клиенту передать код 404. Появился в HTTP/1.1.

411 — (Length Required — Требуется длина)

Для указанного ресурса клиент должен указать Content-Length в заголовке запроса. Без указания этого поля не стоит делать повторную попытку запроса к серверу по данному URI. Такой ответ естественен для запросов типа POST и PUT. Например, если по указанному URI производится загрузка файлов, а на сервере стоит ограничение на их объём. Тогда разумней будет проверить в самом начале заголовок Content-Length и сразу отказать в загрузке, чем провоцировать бессмысленную нагрузку, разрывая соединение, когда клиент действительно пришлёт слишком объёмное сообщение.

412 — (Precondition Failed — Предварительное условие не выполнено)

Возвращается, если ни одно из условных полей заголовка запроса не было выполнено.

Когда клиент указывает rest API выполнять запрос только при выполнении определенных условий, а API не может выполнить запрос при таких условиях, то возвращается ответ 412.

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

413 — (Request Entity Too Large — Сущность запроса слишком большая)

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

Если проблема временная, то рекомендуется в ответ сервера включить заголовок Retry-After с указанием времени, по истечении которого можно повторить аналогичный запрос.

414 — (Request-URI Too Long — Запрос-URI Слишком длинный)

Сервер не может обработать запрос из-за слишком длинного указанного URL. Эту редкую ошибку можно спровоцировать, например, когда клиент пытается передать длинные параметры через метод GET, а не POST, когда клиент попадает в «чёрную дыру» перенаправлений (например, когда префикс URI указывает на своё же окончание), или когда сервер подвергается атаке со стороны клиента, который пытается использовать дыры в безопасности, которые встречаются на серверах с фиксированной длиной буфера для чтения или обработки Request-URI.

415 (Unsupported Media Type — Неподдерживаемый медиа тип)

Сообщение об ошибке 415 указывает, что API не может обработать предоставленный клиентом Тип медиа, как указано в заголовке запроса Content-Type.

Например, запрос клиента содержит данные в формате application/xml, а API готов обработать только application/json. В этом случае клиент получит ответ 415.

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

428 — (Precondition Required — Требуется предварительное условие)

Код состояния 428 указывает, что исходный сервер требует, чтобы запрос был условным.

Его типичное использование — избежать проблемы «потерянного обновления», когда клиент ПОЛУЧАЕТ состояние ресурса, изменяет его и ОТПРАВЛЯЕТ обратно на сервер, когда тем временем третья сторона изменила состояние на сервере, что привело к конфликту. Требуя, чтобы запросы были условными, сервер может гарантировать, что клиенты работают с правильными копиями.

Ответы с этим кодом состояния ДОЛЖНЫ объяснять, как повторно отправить запрос.

429 — (Too Many Requests — Слишком много запросов)

Пользователь отправил слишком много запросов за заданный промежуток времени.

Представления ответа ДОЛЖНЫ включать подробности, объясняющие условие, и МОГУТ включать заголовок Retry-After, указывающий, как долго ждать, прежде чем делать новый запрос.

431 — (Request Header Fields Too Large — Слишком большие поля заголовка запроса)

Код состояния 431 указывает на то, что сервер не желает обрабатывать запрос, поскольку его поля заголовка слишком велики. Запрос МОЖЕТ быть отправлен повторно после уменьшения размера полей заголовка запроса.

Его можно использовать как в случае, когда совокупность полей заголовка запроса слишком велика, так и в случае неисправности одного поля заголовка. В последнем случае представление ответа ДОЛЖНО указывать, какое поле заголовка было слишком большим.

444 — (No Response — Нет ответа) (Nginx)

Код ответа Nginx. Сервер не вернул информацию и закрыл соединение. (полезно в качестве сдерживающего фактора для вредоносных программ)

451 — (Unavailable For Legal Reasons — Недоступен по юридическим причинам)

Доступ к ресурсу закрыт по юридическим причинам. Наиболее близким из существующих является код 403 Forbidden (сервер понял запрос, но отказывается его обработать). Однако в случае цензуры, особенно когда это требование к провайдерам заблокировать доступ к сайту, сервер никак не мог понять запроса — он его даже не получил. Совершенно точно подходит другой код: 305 Use Proxy. Однако такое использование этого кода может не понравиться цензорам. Было предложено несколько вариантов для нового кода, включая «112 Emergency. Censorship in action» и «460 Blocked by Repressive Regime»

500 * (Internal Server Error — Внутренняя ошибка сервера)

Общий ответ при ошибке в коде. Универсальное сообщение о внутренней ошибке сервера, когда никакое более определенное сообщение не подходит.

Большинство веб-платформ автоматически отвечают этим кодом состояния, когда при выполнении кода обработчика запроса возникла ошибка.

Ошибка 500 никогда не зависит от клиента, поэтому для клиента разумно повторить точно такой же запрос, и надеяться что в этот раз сервер отработает без ошибок.

501 (Not Implemented — Не реализован)

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

Если же метод серверу известен, но он не применим к данному ресурсу, то нужно вернуть ответ 405.

502 — (Bad Gateway — Плохой шлюз)

Сервер, выступая в роли шлюза или прокси-сервера, получил некорректный ответ от вышестоящего сервера, к которому он обратился. Появился в HTTP/1.0.

503 — (Service Unavailable — Служба недоступна)

Сервер не может обработать запрос из-за временной перегрузки или технических работ. Это временное состояние, из которого сервер выйдет через какое-то время. Если это время известно, то его МОЖНО передать в заголовке Retry-After.

504 — (Gateway Timeout — Таймаут шлюза)

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

505 — (HTTP Version Not Supported — Версия HTTP не поддерживается)

Сервер не поддерживает или отказывается поддерживать указанную в запросе версию протокола HTTP.

510 — (Not Extended — Не расширен)

В запросе не соблюдена политика доступа к ресурсу. Сервер должен отправить обратно всю информацию, необходимую клиенту для отправки расширенного запроса. Указание того, как расширения информируют клиента, выходит за рамки данной спецификации.

Источники и более подробная информация:

  • https://restapitutorial.ru/httpstatuscodes.html
  • https://www.restapitutorial.com/httpstatuscodes.html
  • https://restfulapi.net/http-status-codes/
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/428

REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result. RFC 2616 defines the Status-Line syntax as shown below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

HTTP defines these standard status codes that can be used to convey the results of a client’s request. The status codes are divided into five categories.

  • 1xx: Informational – Communicates transfer protocol-level information.
  • 2xx: Success – Indicates that the client’s request was accepted successfully.
  • 3xx: Redirection – Indicates that the client must take some additional action in order to complete their request.
  • 4xx: Client Error – This category of error status codes points the finger at clients.
  • 5xx: Server Error – The server takes responsibility for these error status codes.

1xx Status Codes [Informational]

Status Code

Description

100 Continue

An interim response. Indicates to the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed.

101 Switching Protocol

Sent in response to an Upgrade request header from the client, and indicates the protocol the server is switching to.

102 Processing (WebDAV)

Indicates that the server has received and is processing the request, but no response is available yet.

103 Early Hints

Primarily intended to be used with the Link header. It suggests the user agent start preloading the resources while the server prepares a final response.

2xx Status Codes [Success]

Status Code

Description

200 OK

Indicates that the request has succeeded.

201 Created

Indicates that the request has succeeded and a new resource has been created as a result.

202 Accepted

Indicates that the request has been received but not completed yet. It is typically used in log running requests and batch processing.

203 Non-Authoritative Information

Indicates that the returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. The set presented MAY be a subset or superset of the original version.

204 No Content

The server has fulfilled the request but does not need to return a response body. The server may return the updated meta information.

205 Reset Content

Indicates the client to reset the document which sent this request.

206 Partial Content

It is used when the Range header is sent from the client to request only part of a resource.

207 Multi-Status (WebDAV)

An indicator to a client that multiple operations happened, and that the status for each operation can be found in the body of the response.

208 Already Reported (WebDAV)

Allows a client to tell the server that the same resource (with the same binding) was mentioned earlier. It never appears as a true HTTP response code in the status line, and only appears in bodies.

226 IM Used

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.

3xx Status Codes [Redirection]

Status Code

Description

300 Multiple Choices

The request has more than one possible response. The user-agent or user should choose one of them.

301 Moved Permanently

The URL of the requested resource has been changed permanently. The new URL is given by the Location header field in the response. This response is cacheable unless indicated otherwise.

302 Found

The URL of the requested resource has been changed temporarily. The new URL is given by the Location field in the response. This response is only cacheable if indicated by a Cache-Control or Expires header field.

303 See Other

The response can be found under a different URI and SHOULD be retrieved using a GET method on that resource.

304 Not Modified

Indicates the client that the response has not been modified, so the client can continue to use the same cached version of the response.

305 Use Proxy (Deprecated)

Indicates that a requested response must be accessed by a proxy.

306 (Unused)

It is a reserved status code and is not used anymore.

307 Temporary Redirect

Indicates the client to get the requested resource at another URI with same method that was used in the prior request. It is similar to 302 Found with one exception that the same HTTP method will be used that was used in the prior request.

308 Permanent Redirect (experimental)

Indicates that the resource is now permanently located at another URI, specified by the Location header. It is similar to 301 Moved Permanently with one exception that the same HTTP method will be used that was used in the prior request.

4xx Status Codes (Client Error)

Status Code

Description

400 Bad Request

The request could not be understood by the server due to incorrect syntax. The client SHOULD NOT repeat the request without modifications.

401 Unauthorized

Indicates that the request requires user authentication information. The client MAY repeat the request with a suitable Authorization header field

402 Payment Required (Experimental)

Reserved for future use. It is aimed for using in the digital payment systems.

403 Forbidden

Unauthorized request. The client does not have access rights to the content. Unlike 401, the client’s identity is known to the server.

404 Not Found

The server can not find the requested resource.

405 Method Not Allowed

The request HTTP method is known by the server but has been disabled and cannot be used for that resource.

406 Not Acceptable

The server doesn’t find any content that conforms to the criteria given by the user agent in the Accept header sent in the request.

407 Proxy Authentication Required

Indicates that the client must first authenticate itself with the proxy.

408 Request Timeout

Indicates that the server did not receive a complete request from the client within the server’s allotted timeout period.

409 Conflict

The request could not be completed due to a conflict with the current state of the resource.

410 Gone

The requested resource is no longer available at the server.

411 Length Required

The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field.

412 Precondition Failed

The client has indicated preconditions in its headers which the server does not meet.

413 Request Entity Too Large

Request entity is larger than limits defined by server.

414 Request-URI Too Long

The URI requested by the client is longer than the server can interpret.

415 Unsupported Media Type

The media-type in Content-type of the request is not supported by the server.

416 Requested Range Not Satisfiable

The range specified by the Range header field in the request can’t be fulfilled.

417 Expectation Failed

The expectation indicated by the Expect request header field can’t be met by the server.

418 I’m a teapot (RFC 2324)

It was defined as April’s lool joke and is not expected to be implemented by actual HTTP servers. (RFC 2324)

420 Enhance Your Calm (Twitter)

Returned by the Twitter Search and Trends API when the client is being rate limited.

422 Unprocessable Entity (WebDAV)

The server understands the content type and syntax of the request entity, but still server is unable to process the request for some reason.

423 Locked (WebDAV)

The resource that is being accessed is locked.

424 Failed Dependency (WebDAV)

The request failed due to failure of a previous request.

425 Too Early (WebDAV)

Indicates that the server is unwilling to risk processing a request that might be replayed.

426 Upgrade Required

The server refuses to perform the request. The server will process the request after the client upgrades to a different protocol.

428 Precondition Required

The origin server requires the request to be conditional.

429 Too Many Requests

The user has sent too many requests in a given amount of time (“rate limiting”).

431 Request Header Fields Too Large

The server is unwilling to process the request because its header fields are too large.

444 No Response (Nginx)

The Nginx server returns no information to the client and closes the connection.

449 Retry With (Microsoft)

The request should be retried after performing the appropriate action.

450 Blocked by Windows Parental Controls (Microsoft)

Windows Parental Controls are turned on and are blocking access to the given webpage.

451 Unavailable For Legal Reasons

The user-agent requested a resource that cannot legally be provided.

499 Client Closed Request (Nginx)

The connection is closed by the client while HTTP server is processing its request, making the server unable to send the HTTP header back.

5xx Status Codes (Server Error)

Status Code

Description

500 Internal Server Error

The server encountered an unexpected condition that prevented it from fulfilling the request.

501 Not Implemented

The HTTP method is not supported by the server and cannot be handled.

502 Bad Gateway

The server got an invalid response while working as a gateway to get the response needed to handle the request.

503 Service Unavailable

The server is not ready to handle the request.

504 Gateway Timeout

The server is acting as a gateway and cannot get a response in time for a request.

505 HTTP Version Not Supported (Experimental)

The HTTP version used in the request is not supported by the server.

506 Variant Also Negotiates (Experimental)

Indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper endpoint in the negotiation process.

507 Insufficient Storage (WebDAV)

The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.

508 Loop Detected (WebDAV)

The server detected an infinite loop while processing the request.

510 Not Extended

Further extensions to the request are required for the server to fulfill it.

511 Network Authentication Required

Indicates that the client needs to authenticate to gain network access.

6. REST Specific HTTP Status Codes

200 (OK)

It indicates that the REST API successfully carried out whatever action the client requested and that no more specific code in the 2xx series is appropriate.

Unlike the 204 status code, a 200 response should include a response body. The information returned with the response is dependent on the method used in the request, for example:

  • GET an entity corresponding to the requested resource is sent in the response;
  • HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;
  • POST an entity describing or containing the result of the action;
  • TRACE an entity containing the request message as received by the end server.

201 (Created)

A REST API responds with the 201 status code whenever a resource is created inside a collection. There may also be times when a new resource is created as a result of some controller action, in which case 201 would also be an appropriate response.

The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.

The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with a 202 (Accepted) response instead.

202 (Accepted)

A 202 response is typically used for actions that take a long while to process. It indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, or even maybe disallowed when processing occurs.

Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed.

The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor (job queue location) or some estimate of when the user can expect the request to be fulfilled.

204 (No Content)

The 204 status code is usually sent out in response to a PUT, POST, or DELETE request when the REST API declines to send back any status message or representation in the response message’s body.

An API may also send 204 in conjunction with a GET request to indicate that the requested resource exists, but has no state representation to include in the body.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view. However, any new or updated metainformation SHOULD be applied to the document currently in the user agent’s dynamic view.

The 204 response MUST NOT include a message-body and thus is always terminated by the first empty line after the header fields.

301 (Moved Permanently)

The 301 status code indicates that the REST API’s resource model has been significantly redesigned, and a new permanent URI has been assigned to the client’s requested resource. The REST API should specify the new URI in the response’s Location header, and all future requests should be directed to the given URI.

You will hardly use this response code in your API as you can always use the API versioning for the new API while retaining the old one.

302 (Found)

The HTTP response status code 302 Found is a common way of performing URL redirection. An HTTP response with this status code will additionally provide a URL in the Location header field. The user agent (e.g., a web browser) is invited by a response with this code to make a second. Otherwise identical, request to the new URL specified in the location field.

Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g., POST). RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

303 (See Other)

A 303 response indicates that a controller resource has finished its work, but instead of sending a potentially unwanted response body, it sends the client the URI of a response resource. The response can be the URI of the temporary status message, or the URI to some already existing, more permanent, resource.

Generally speaking, the 303 status code allows a REST API to send a reference to a resource without forcing the client to download its state. Instead, the client may send a GET request to the value of the Location header.

The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

304 (Not Modified)

This status code is similar to 204 (“No Content”) in that the response body must be empty. The critical distinction is that 204 is used when there is nothing to send in the body, whereas 304 is used when the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.

In such a case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.

Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.

307 (Temporary Redirect)

A 307 response indicates that the REST API is not going to process the client’s request. Instead, the client should resubmit the request to the URI specified by the response message’s Location header. However, future requests should still use the original URI.

A REST API can use this status code to assign a temporary URI to the client’s requested resource. For example, a 307 response can be used to shift a client request over to another host.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s). If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

400 (Bad Request)

400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can be like malformed request syntax, invalid request message parameters, or deceptive request routing etc.

The client SHOULD NOT repeat the request without modifications.

401 (Unauthorized)

A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. It may have provided the wrong credentials or none at all. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.

The client MAY repeat the request with a suitable Authorization header field. If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.

403 (Forbidden)

A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it, i.e., the user does not have the necessary permissions for the resource. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”).

Authentication will not help, and the request SHOULD NOT be repeated. Unlike a 401 Unauthorized response, authenticating will make no difference.

404 (Not Found)

The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may be available in the future. Subsequent requests by the client are permissible.

No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

405 (Method Not Allowed)

The API responds with a 405 error to indicate that the client tried to use an HTTP method that the resource does not allow. For instance, a read-only resource could support only GET and HEAD, while a controller resource might allow GET and POST, but not PUT or DELETE.

A 405 response must include the Allow header, which lists the HTTP methods that the resource supports. For example:

Allow: GET, POST

406 (Not Acceptable)

The 406 error response indicates that the API is not able to generate any of the client’s preferred media types, as indicated by the Accept request header. For example, a client request for data formatted as application/xml will receive a 406 response if the API is only willing to format data as application/json.

If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.

412 (Precondition Failed)

The 412 error response indicates that the client specified one or more preconditions in its request headers, effectively telling the REST API to carry out its request only if certain conditions were met. A 412 response indicates that those conditions were not met, so instead of carrying out the request, the API sends this status code.

415 (Unsupported Media Type)

The 415 error response indicates that the API is not able to process the client’s supplied media type, as indicated by the Content-Type request header. For example, a client request including data formatted as application/xml will receive a 415 response if the API is only willing to process data formatted as application/json.

For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

500 (Internal Server Error)

500 is the generic REST API error response. Most web frameworks automatically respond with this response status code whenever they execute some request handler code that raises an exception.

A 500 error is never the client’s fault, and therefore, it is reasonable for the client to retry the same request that triggered this response and hope to get a different response.

The API response is the generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

501 (Not Implemented)

The server either does not recognize the request method, or it cannot fulfill the request. Usually, this implies future availability (e.g., a new feature of a web-service API).

References :

https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

Error handling is one of the key components of REST API best practices.

Hope for the best, prepare for the worst.

In this article, we’ll explore everything you need to know about handling errors in REST APIs.

Best practices of error handling in REST APIs consist of:

1. HTTP Status Codes

HTTP status codes are the most important indicator of errors in REST APIs.

Out of five categories of HTTP status codes, two are used for errors:

  • 400 range: Client Errors — where something is wrong on the user’s end
  • 500 range: Protocol Errors — indicating issues from within in terms of fault processing.

Most common HTTP error status codes

Here is a table of the most common HTTP error codes and their explanations:

HTTP Status Code Explanation
400 Bad Request

The request was malformed or invalid, and the server could not process
it.

401 Unauthorized

The request requires authentication, and the client did not provide
valid credentials.

403 Forbidden

The client does not have permission to access the requested resource.

404 Not Found The requested resource could not be found on the server.
405 Method Not Allowed The requested method is not supported by the resource.
429 Too Many Requests

The client has made too many requests in a specified time period and is
being rate-limited by the server.

500 Internal Server Error

An unexpected error occurred on the server, and it was unable to process
the request.

503 Service Unavailable

The server is temporarily unable to handle the request due to
maintenance or overloading.

Read more: HTTP Bad Request vs Not Found


HTTP error status codes tell us that the request failed, but they don’t provide domain-specific details. That’s why we add error codes to the response body.

2. REST API Error Codes

REST API error codes are domain-specific error identifiers that proved more detailed information about the error.

Error codes are communicated to the client in the response body along with a relevant error message.

Stripe API error codes example
Stripe API: Examples of error codes when authorizing with an invalid credit card

3. REST API Error message

It’s important to include the error message in the response body because it helps our API consumers understand the error context.

REST API Error Message Example

The error message is usually a one sentence that should tell more than what we know from the status code.

For example, returning the status code 401 Unauthorized with the error message Unauthorized request doesn’t provide much information on why the request was unauthorized. A better error message could be This feature is not in your access scope.

The response body of an errored request should not contain the error stack trace.

4. Error Trace ID

An error trace ID is a unique identifier that is generated when an error occurs.

It can be used to track and trace the error throughout the system. The unique ID makes it easier for API developers to identify, diagnose, and resolve issues.

The error trace ID is typically included in the response body of an error response. It can also be logged by the API and other systems along the request-response path, providing a complete and detailed trace of the error.

REST API error trace ID
Example of the trace ID from the Facebook API

Having a unique error trace ID is particularly useful in microservice architectures, where multiple services may be involved in processing a single request. The error trace ID can be used to correlate errors across multiple services and to trace the request-response path through the system.

5. Error Message Formatting

If you’re using JSON, using the application/problem+json (Problem Detail) media type is the best way to format the error response.

Problem Detail Content Type Example for REST API error handling
Problem Detail response example from Backend.AI

Using the «problem detail» response body just means putting together all the best practices we’ve talked about.
The problem detail body must include the error:

  • Type or status code — unique error identifier
  • Title
  • Detail — Brief error explanation.

Internet Engineering Task Force (IETF) defines a «problem detail» approach in RFC7807.

Negative Testing REST API

Negative Testing is a REST API feature that lets API clients simulate errors.

The sandbox API defines request bodies you can use to guarantee a certain error response.

Negative Testing is crucial for developing a robust integration because it’s impossible to organically test out all the error states.

PayPal REST API Documentation
PayPal Orders REST API supports negative testing

HTTP Error Statuses vs Error Codes

The main difference between HTTP error status codes and error codes is that HTTP error status codes are standardized and widely recognized across the web, while error codes are specific to a particular application or service.

HTTP error status codes are three-digit codes that indicate the outcome of a request, such as success (200 OK), client error (4xx) or server error (5xx). They provide a basic level of error information and are widely understood by API clients.

Error codes, on the other hand, are custom codes that provide more detailed information about an error. They can be used to provide additional context about the error, such as indicating the specific validation error or the type of resource that caused the error. Error codes can be communicated to the client in the response body along with a relevant error message.

REST API Error Handling Best Practices Summary

Best Practices:

  • HTTP Status Codes: Use HTTP status codes to indicate errors in REST APIs.
  • Error Codes: Use domain-specific error codes to provide more detailed information about the error.
  • Error Messages: Include error messages in the response body to help API consumers understand the error context.
  • Error Trace ID: Use a unique error trace ID to track and trace errors throughout the system.
  • Error Message Format: Use the application/problem+json (Problem Detail) media type to format error responses in JSON.

FAQ: REST API Error Handling

Should the response body include the HTTP status code?

The response body should not include the HTTP status code.

Including it in the response body adds to the network payload and it is redundant.

Why is it important to use proper HTTP error status codes?

It’s important to use proper HTTP error statuses because they are standardized across the web.

They are widely recognized and understood by API clients, tools, and services.

For example, Application Performance Monitoring tools (APM) automatically categorize errors based on their HTTP status codes and provide valuable insights into the performance and health of the API. If an error happens and we return the «200 OK» status, an APM wouldn’t catch it.

Similarly, API gateways and load balancers can be configured to route requests based on the HTTP status code, allowing for fine-grained control over the API behavior.

Should error response include the exception message?

Based on RFC7807, error response should not include the exception message or stack trace:

Problem details are not a debugging tool for the underlying implementation; rather, they are a way to expose greater detail about the HTTP interface itself. — RFC7807

Published on:

Если сервер корректно обработал запрос, то ответ у нас не должен говорить, что произошла ошибка.

В респонсе должны возвращаться статусы ошибок, которые можно сопоставить с http кодами. НО использовать все (около 70) коды — нецелесообразно, лучше ограничитьтся 3-10 вариантов, чтоб не запутывать разработчиков и тестровщиков.

Возможно только 3 варианта ответов API:

  1. Запрос прошел успешно (200 — OK, 201: Created, 204 — no content, 304 Not Modified (Данные не изменились))
  2. Клиент отправил некорректный запрос — возвращаем клиентские ошибки (400 Bad Request, 401: Unauthorized, 403: Forbidden, 405: Method Not Allowed, )
  3. Произошла ошибка при обработке данных — серверная ошибка (500 Internal server Error, 503: Service Unavailable, 501: Not Implemented)

Если 3-х кодов вам недостаточно — возьмите еще:

  1. 201 Created (Запись создана)
  2. 204 No Content
  3. 304 Not Modified (Данные не изменились)
  4. 404 Not Found (Данные не найдены)
  5. 401 Unauthorized (Неавторизованный доступ)
  6. 403 Forbidden (Доступ запрещен)

(из статьи https://habrahabr.ru/post/181988/ )

Рассмотрим на примере поиска пользователя по имени.

Например, я отправляю GET /users=?name=Ivan

но нет у нас ни одного Ivan’а в базе, тогда я ожидаю, что сервер мне сообщит о том, что ни одного Ivan’а не найдено.

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

200 и пустое тело ответа — это минимум, что я должна получить

204 -No Content, не отсылается обычно для GET запросов, но отсылается для POST,  PUT, UPDATE, DELETE нет

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

Еще раз :

Сервер корректно обработал запрос — вернули «Запрос прошел успешно»

Клиент прислал некорректный запрос и сервер понимает, что клиент в запросе отправил что-то невалидное = возвращаем вариации 4ХХ

Сервер не смог обработать запрос — возвращаем ошибки сервера.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404

некорректно отправленный с клиента запрос =


Worse than encountering an error is encountering an “unspecified” error. If you don’t want your REST API to give users a hard time, explain the errors and their reasons clearly. Do not forget to use HTTP status codes while doing this. Standard HTTP status codes will suffice for a general description of almost any error.

HTTP status codes (HTTP response codes) are the codes returned in response to an HTTP request sent from the client to the server where a web page is hosted. When a browser (client) wants to connect to the web page, the server hosting the page returns a response (response) related to the status of the relevant page. In this process, which takes place during each browser-server interaction, the server returns a 3 (digit) numbered description in response. This response is contained in the HTTP response header and is not directly part of the page content.

HTTP codes are divided into different meanings and groups according to the beginning of the first of the 3 digits. If a response starts with code 3, it is part of a routing group. At this point, whether the relevant redirect is permanent, temporary or a security-related redirect is determined in the last number among the 2 numbers that will follow after the number 3.

HTTP Status Classes

  • 1xx (100 Code Responses): 1xx HTTP Status codes are responses where the user is notified that the request is in progress on the server side. For example, the HTTP 100 response is the one reporting that the request is currently being processed. This response is transmitted to the browser but not reflected to the user screen.
  • 2xx (200-Code Responses): 2xx HTTP Status codes are responses from the browser to the server for the page, reporting that the operation was successful. In HTTP 2xx coded responses, it is reported that the server has successfully responded to the request from the browser and the page can be opened. For example, in http 200 “OK” coded responses, the page can be seen clearly in the user’s browser after the request.
  • 3xx (300-Code Responses): 3xx HTTP status codes are responses to inform the server that the request from the browser to the web page has been redirected to a different page. In other words, when a request is sent from the browser for pages with 3xx status codes, the server notifies that the relevant page is redirected to a different page with HTTP 3xx coded responses and redirects the user to the new page.
  • 4xx (400-Code Responses): 4xx HTTP status codes are responses where a user-generated error has occurred. In other words, when a response with HTTP 4xx error code is sent to the browser, it is reported that the source of the error is the client, that is, the user. However, the user here should not be perceived as the person who sent the request only from the browser. 4xx HTTP error codes may occur after any action taken on the site hosting the web page.
  • 5xx (500 Code Responses): 5xx HTTP status codes are the responses that a server-related error occurred during the request sent from the browser.

HTTP Status Codes List

You can find the most common HTTP response codes in the web world in the list below;

Http Status code 404

1xx Informative HTTP Status Codes

STATUS CODE EXPLANATION
HTTP 100 (Continue) It is the response that the request sent to the server by the user (client) is processed properly and that there is no problem with the request with the HTTP status code. After the HTTP 100 code is sent to the browser & user, the user is expected to continue with the request.
HTTP 101 (Switching Protocols) If the client asks the server to change the protocol and provides notification in the header, the positive response from the server is sent with HTTP 101. With the HTTP 101 response code, it is presented to the browser (client) where the request is made, where the protocol is changed.
HTTP 102 (Processing) The HTTP 102 status code is the response that is reported by the client that the request is being processed by the server. The main purpose of sending this response is to prevent time out of the request sent by the client to the server.
HTTP 103 (Early Hints) The HTTP 103 status code is used to return some response headers before the server responds to the request sent by the client to the server.

2xx Successful HTTP Status Codes

STATUS CODE EXPLANATION
HTTP 200 (OK) The request sent by the client to the server has been answered successfully. Depending on the nature of the request sent to the server, there is optional data in the response sent from the server.
HTTP 201 (Created) The HTTP 201 status code is used when the server successfully responds to the request from the client and creates a suitable new resource for the request.
HTTP 202 (Accepted) It is used when the request sent by the client to the server is accepted by the server, but the request is still being processed on the server side. It is not certain whether the request from the client will be completed after the response returned with the HTTP 202 status code. The request may fail.
HTTP 203 (Non-Authoritative Information) The HTTP 203 status code is sent when the request sent by the client is successfully answered by the server, but the metadata sent from the server has changed while reaching the client. At this point, the response from the server to change while reaching the client is usually experienced in the case of proxy use.
HTTP 204 (No Content) The HTTP 204 status code is used when the request sent by the client has been successfully processed by the server but there is no content to be returned to the client. The user is expected to send a request for old or different content.
HTTP 205 (Reset Content) The HTTP 205 status code is sent when the request sent by the client is answered successfully and the request creates a change in the image of the document (resetting the document, etc.). So, for example, when the user presses the reset button on an HTML document, the HTTP 205 status code is returned in response.
HTTP 206 (Partial Content) If the client (browser) uses range headers in the header section, the HTTP 206 status code is used. When this header is used, the client can pause and continue the document sent from the server as requested. For example; An example of this is when you can stop and start the download file from the server you are making a request to.
HTTP 207 (Multi Status) If an XML Document containing more than one HTTP status code is returned in the response of the server to the request sent by the client, the HTTP 207 status code is used. The data in the sent XML document takes part in different studies independently of the request.

3xx Redirect HTTP Status Codes

STATUS CODE EXPLANATION
HTTP 300 (Multiple Choices) The HTTP 300 status code is used in cases where a large number of different resource returns can be made in response from the server related to the request transmitted by the client to the server. From the resources returned by the server as a response, the client (user) must make a choice. If the server prefers one of these preferable sources, it is specified in the locationheader section.
HTTP 301 (Permanent Redirect) The HTTP 301 status code is sent by the server as a response when the requested web page is completely moved by the client. If the request sent by the user to the server is made as Get or Head, the user (client) is sent directly to the new forwarded URL address.
HTTP 302 (Temporary Redirect) In the event that the requested web page is temporarily moved to a different URL address, the server sends the HTTP 302 status code as a response. With this response, the server sends a message to the client that it should continue to use this URL to reach the resource that it wants to reach. Unlike a 301 redirect, the redirect that occurs here is not considered a valid redirect by search engine bots and pagerank is not transferred. (Accepted provisionally)
HTTP 303 (See Others) If the request forwarded to the server by the client is not possible to getfetched with this URL, the server returns HTTP 303 code in response. When the request from the user about the relevant web page is made with get and the URL cannot be answered by the server with get, the server sends the HTTP 303 code to the client to make a request in a different way or to request a different URL.

The resource requested by the client will be discoverable in request formats like post, delete etc, but if it is not available with Get, HTTP 303 will be returned as a response.

HTTP 304 (Not Modified) If the web page or document sent by the client to the server has not undergone any changes since the user’s last connection, an HTTP 304 response code is returned by the server. The main purpose here is to trigger the use of Cache and increase opening speeds by notifying the client of the unmodified documents.
HTTP 305 (Use Proxy) In case the web page requested by the client is viewable only with the proxy (different location header), the server returns the HTTP 305 status code as a response.
HTTP 307 ( Temporary Redirect) If the address sent by the client is found by the server, but broadcasting from a different URL address, an HTTP 307 status code is returned in response. As with the HTTP 302 status code, the server sends this response and sends the message to the client that it should continue to use this URL to reach the requested resource.

The main difference between 302 redirect and 307 is that the form of the request made in 307 and the basic part of the request remain unchanged.

HTTP 308 (Permanent Redirect) The HTTP 308 status code is returned by the server as a response to notify that the request sent from the client to the server as an alternative to HTTP 301 has been successfully moved to a different URL. Unlike HTTP 301 redirect, HTTP request method is not allowed to change in HTTP 308 redirect.

4xx Client Error HTTP Status Codes

STATUS CODE EXPLANATION
HTTP 400 (Bad Request) It is the HTTP status code sent when the request sent by the client to the server cannot be answered due to an incorrect request (syntax error).
HTTP 401 (Unauthorized) HTTP 401 status code is returned by the server in order to share the information that the operation related to the requested web page by the client cannot be performed without authorization. In order for the authorization process to be performed, the server informs the client how the authorization can be done by returning the WWW_Authenticate server response header.
HTTP 402 (Payment Required) The information that the user has to pay in order to view the web page requested by the client is reported by the server with the HTTP 402 status code. Generally, it is possible to encounter HTTP 402 error codes on a page to be shown in the next stage or on pages whose usage is limited to certain limits.
HTTP 403 (Forbidden) In cases where the request forwarded by the client to the server is fulfillable by the server, but the client is not authorized to access this resource, the HTTP 403 status code is returned in response. The client is prompted not to repeat the unauthorized request.
HTTP 404 (Not Found) When the server cannot find resources related to the web page requested by the client, it returns an HTTP 404 status code in response. It is the most common mistake in the web world.
HTTP 405 (Method Not Allowed) HTTP 405 status code is used when the HTTP request method (GET or POST) of the request sent by the client is not allowed. Generally, it is encountered in cases where the server recognizes the request method, but the resource to be connected does not allow this method. Likewise, this error code is encountered in cases where request methods that the server does not recognize are used.

Example: WebDav

HTTP 406 (Not Acceptable) In cases where the request sent from the client to the server cannot be served as the request was made (form), HTTP 406 status code is returned by the server as a response. For example, if the client sends a request over a gif format to an image that exists only as png on the server, the server returns HTTP 406 in response to this request.
HTTP 407 (Proxy Authentication Required) Similar to the HTTP 401 request, in the case of the HTTP 407 status code, the server requests verification from the client sending a request for a document. In the case where a proxy is used, the server also requests the proxy’s authorization and asks the client to verify the proxy before connecting.
HTTP 408 (Request Timed Out) If the request sent by the client to the server cannot be completed by the server within the specified time, the HTTP 408 status code is returned as a response.
HTTP 409 (Conflict) In cases where processing the request sent by the client would cause confusion in the requested resource, the server returns the HTTP 409 status code in response.
HTTP 410 (Gone) In cases where the resource requested by the client is permanently deleted from the server and will not be returned, the server returns the HTTP 410 status code in response. In particular, the information that a content is permanently deleted is given to search engines with the HTTP 410 status code.
HTTP 411 (Length Header Required) If the request sent from the client cannot be processed by the server because it does not contain a content-length header, an HTTP 411 status code is returned in response.
HTTP 412 (Precondition Failed) HTTP 412 is returned in response if a condition communicated to the server by the client cannot be met.
HTTP 413 (Request Entity Too Large) In cases where the size of the file request forwarded by the client to the server is too large, the server rejects the operation and returns the HTTP 413 status code in response.
HTTP 414 (Requested URL Too Large) When the URL requested by the client is too large (long), the server sends the HTTP 414 status code as a response. There is no definite limit on URL length due to HTTP standards, but URL size may be limited due to server configuration settings.
HTTP 415 (Unsupported Media Type) In cases where the media type of the file requested by the client is not supported by the server, the HTTP 415 status code is returned in response.
HTTP 416 (Requested range not satisfiable) If part of the resource requested by the client is invalid or unavailable, the server returns the HTTP 416 status code in response. Such situations often appear with partial (progressive) downloads.
HTTP 417 (Expectation Failed) If the server does not meet the conditions in the expect header field in the header of the request sent by the client, it returns the HTTP 417 status code in response.
HTTP 421 (Misdirected Request) When the request sent by the client is forwarded to a server where the response cannot be sent, the HTTP 421 status code is returned in response.
HTTP 422 (Unprocessable Entity) If the request sent by the client to the server contains semantic errors, the server cannot process the request and returns HTTP 422 status code in response.
HTTP 423 (Locked) The information that the resource requested by the client is currently a locked resource is reported by the server with the HTTP 423 status code.
HTTP 424 (Failed Dependency) The server returns the http 424 status code when the resource requested by the client cannot be processed because the previous resource related to the relevant resource could not be processed.
HTTP 425 (Too Early) The HTTP 425 status code is sent as a response when a request to the server is in a replayable state and the server does not want to process the request.
HTTP 426 (Upgrade Required) In case the requesting client needs to upgrade to Transport Layer Security (TLS / 1.0), the HTTP 426 status code is returned in response.
HTTP 428 (Precondition Required) An HTTP 428 status code is returned in response when the server requests conditions to be specified first so that the request sent by the client to the server can be processed.
HTTP 429 (Too Many Requests) When a large number of requests are sent by the client to the server in a limited time, the server returns the HTTP 429 status code in response.
HTTP 451 (Unavailable For Legal Reasons) If the resource the client wants to access is legally blocked in a region or country, the server returns the HTTP 451 status code in response. The reason for this blocking may be copyright, legal ban (blackout) or national blocking.

5xx Server HTTP Status Codes

STATUS CODE EXPLANATION
HTTP 500 (Internal Server Error) When the server is unable to process the request from the client due to an identified internal error, it returns the HTTP 500 status code in response. The server may not be able to process the request for reasons such as errors in the programs on the server, database errors.
HTTP 501 (Not Implemented) The HTTP 501 status code is a response code returned by the server for an error that occurs when the server does not have functions to handle the request from the client. This problem is usually caused by the web host and is solved by the web host (hosting provider).
HTTP 502 (Bad Gateway) In cases where a proxy is used, an HTTP 502 status code is sent to the client in response when one of the servers providing the data streams returns an incomprehensible response code to the other.
HTTP 503 (Service Unavailable) Whenever the server service is unavailable, the server returns an HTTP 503 response to the client. It is usually seen in sites that receive a lot of traffic, after heavy data transfer, in cases where the server swells or the server is taken into maintenance. It can also be seen on small and medium-sized sites if your server is not capable of handling your site’s traffic.
HTTP 504 (Gateway Time-out) In the case of a connection using a proxy, the HTTP 504 status code is returned to the client as a response, in case the proxy server cannot process the request due to timeout.
HTTP 505 (HTTP Version Not Supported) An HTTP 505 status code is returned in response when the HTTP version the request is sent to is not supported.
HTTP 507 (Insufficient Storage) When the request from the client to the server cannot be processed due to insufficient storage space of the server on the server side, the server returns an HTTP 507 status code in response.
HTTP 509 (Bandwidth Limit Exceeded) When a client-to-server request is rejected because it would fill the server’s traffic bandwidth if processed, the server returns the HTTP 509 status code in response.
HTTP 511 (Network Authentication Required) The HTTP 511 status code is returned in response when the client must first authenticate before it can establish a connection to the network.
HTTP 521 (Web Server is Down) The HTTP 521 error is a status code for websites using cloudflare. An HTTP 521 error code is returned in response when the client (browser) establishes a healthy connection to Cloudflare, but Cloudflare cannot connect to the server of the web page. Here, it is reported via cloudflare that the server where the requested web page is located is not responding.

Conclusion

HTTP status codes play a vital role for both developers and users of an application. It gives a clear understanding and direction about the current state of things on a web page. It also helps with search engine optimization and digital marketing.

Понравилась статья? Поделить с друзьями:
  • Regedit ошибка при изменении параметра
  • Rest api выдал ошибку вордпресс
  • Resident evil 5 ошибка windows live
  • Remote control ошибка бмв
  • Register filter driver exception ошибка