For certain resources, my RESTful server only accepts PUT
and POST
requests with JSON objects as the content body, thus requiring a Content-Type
of application/json
instead of application/x-www-form-urlencoded
or multipart/form-data
or anything else.
Malformed JSON (or lack thereof) returns a 400
with the error message taken directly from the exception raised by the JSON parser, for debugging purposes.
Which HTTP error code means that the client sent a request with an unacceptable Content-Type
, even if the server could technically parse the request content?
asked Aug 15, 2012 at 17:08
4
It could be 415 Unsupported Media Type
according to this list: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16.
3rd party edit
From the current RFC9110 HTTP Semantics
The 415 (Unsupported Media Type) status code indicates that the origin
server is refusing to service the request because the content is in a
format not supported by this method on the target resource.The format problem might be due to the request’s indicated
Content-Type or Content-Encoding, or as a result of inspecting the
data directly.If the problem was caused by an unsupported content coding, the
Accept-Encoding response header field (Section 12.5.3) ought to be
used to indicate which (if any) content codings would have been
accepted in the request.On the other hand, if the cause was an unsupported media type, the
Accept response header field (Section 12.5.1) can be used to indicate
which media types would have been accepted in the request.
Source RFC9110 — 415 unsupported media type
surfmuggle
5,0937 gold badges44 silver badges74 bronze badges
answered Aug 15, 2012 at 17:17
William DurandWilliam Durand
5,3891 gold badge25 silver badges37 bronze badges
7
принят и клиент может продолжать присылать запросы либо проигнорировать
этот ответ, если запрос был завершён.
клиента, содержащий заголовок
Upgrade:
, и указывает, чтосервер переключился на протокол, который был указан в заголовке. Эта
возможность позволяет перейти на несовместимую версию протокола и обычно
не используется.
обрабатывает его, но обработка ещё не завершена.
загружены заранее, пока сервер будет подготавливать основной ответ.
RFC 8297 (Experimental).
OK
метода HTTP, который был запрошен:
-
GET: «ПОЛУЧИТЬ». Запрошенный ресурс был найден и передан в теле
ответа. - HEAD: «ЗАГОЛОВОК». Заголовки переданы в ответе.
-
POST: «ПОСЫЛКА». Ресурс, описывающий результат действия сервера на
запрос, передан в теле ответа. -
TRACE: «ОТСЛЕЖИВАТЬ». Тело ответа содержит тело запроса полученного
сервером.
Этот код обычно присылается в ответ на запрос PUT «ПОМЕСТИТЬ».
нет способа с помощью HTTP отправить асинхронный ответ позже, который
будет показывать итог обработки запроса. Это предназначено для случаев,
когда запрос обрабатывается другим процессом или сервером, либо для
пакетной обработки.
которая возвращена, была предоставлена не от исходного сервера, а из
какого-нибудь другого источника. Во всех остальных ситуациях более
предпочтителен код ответа 200 OK.
ответа, которые могут быть полезны, присылаются. Клиент может
использовать их для обновления кешированных заголовков полученных ранее
для этого ресурса.
чтобы сообщить клиенту, что необходимо сбросить отображение документа,
который прислал этот запрос.
присылает заголовок диапазона, чтобы выполнить загрузку отдельно, в
несколько потоков.
«Множественный выбор». Этот код ответа присылается, когда запрос имеет
более чем один из возможных ответов. И User-agent или пользователь
должен выбрать один из ответов. Не существует стандартизированного
способа выбора одного из полученных ответов.
«Перемещён на постоянной основе». Этот код ответа значит, что URI
запрашиваемого ресурса был изменён. Возможно, новый URI будет
предоставлен в ответе.
«Найдено». Этот код ответа значит, что запрошенный ресурс
временно изменён. Новые изменения в URI могут быть доступны в
будущем. Таким образом, этот URI, должен быть использован клиентом в
будущих запросах.
направлять клиента для получения запрашиваемого ресурса в другой URI с
запросом GET.
значит, что запрошенный ресурс не был изменён. Таким образом, клиент
может продолжать использовать кешированную версию ответа.
доступен через прокси. Этот код ответа в основном не поддерживается из
соображений безопасности.
запросы должны использовать указанный прокси.»
получил запрошенный ресурс на другой URL-адрес с тем же методом, который
использовал предыдущий запрос. Данный код имеет ту же семантику, что код
ответа
302 Found
, за исключением того, что агентпользователя не должен изменять используемый метод HTTP: если в первом
запросе использовался
POST
, то во втором запросе такжедолжен использоваться
POST
.
«Перенаправление на постоянной основе». Это означает, что ресурс
теперь постоянно находится в другом URI, указанном в заголовке
Location:
HTTP Response. Данный код ответа имеет ту же
семантику, что и код ответа 301 Moved Permanently
, за
исключением того, что агент пользователя не должен изменять
используемый метод HTTP: если POST
использовался в первом
запросе, POST
должен использоваться и во втором запросе.
Примечание: Это экспериментальный код ответа,
Спецификация которого в настоящее время находится в черновом виде.
из-за неверного синтаксиса.
аутентификация. Статус похож на статус 403, но,в этом случае,
аутентификация возможна.
использования. Первоначальная цель для создания этого кода была в
использовании его для цифровых платёжных систем(на данный момент не
используется).
отказывается дать надлежащий ответ.
ответа, наверно, самый известный из-за частоты его появления в вебе.
деактивирован и не может быть использован. Два обязательных метода,
GET
и HEAD
, никогда не должны бытьдеактивированы и не должны возвращать этот код ошибки.
Этот ответ отсылается, когда веб сервер после выполнения
server-driven content negotiation, не нашёл контента, отвечающего критериям, полученным из user agent.
прокси сервера.
означает, что сервер хотел бы отключить это неиспользуемое соединение.
Этот метод используется все чаще с тех пор, как некоторые браузеры,
вроде Chrome и IE9, стали использовать
HTTP механизмы предварительного соединения
для ускорения сёрфинга (смотрите баг 634278, будущей
реализации этого механизма в Firefox). Также учитывайте, что некоторые
серверы прерывают соединения не отправляя подобных сообщений.
Этот ответ отсылается, когда запрос конфликтует с текущим состоянием
сервера.
Этот ответ отсылается, когда запрашиваемый контент удалён с сервера.
Запрос отклонён, потому что сервер требует указание заголовка
Content-Length
, но он не указан.
выполнить
Размер запроса превышает лимит, объявленный сервером. Сервер может
закрыть соединение, вернув заголовок Retry-After
его обработать
запрос отклонён
Range
не может бытьвыполнен; возможно, он выходит за пределы переданного URI
Expect
, не может быть выполнено сервером.
не знает как обработать.
обработан. Единственные методы, которые сервера должны поддерживать (и,
соответственно, не должны возвращать этот код) —
GET
иHEAD
.
качестве шлюза для получения ответа, нужного для обработки запроса,
получил недействительный (недопустимый) ответ.
причинами являются отключение сервера или то, что он перегружен.
Обратите внимание, что вместе с этим ответом удобная для
пользователей(user-friendly) страница должна отправлять объяснение
проблемы. Этот ответ должен использоваться для временных условий и
Retry-After:
HTTP-заголовок должен, если возможно,содержать предполагаемое время до восстановления сервиса. Веб-мастер
также должен позаботиться о заголовках, связанных с кешем, которые
отправляются вместе с этим ответом, так как эти ответы, связанные с
временными условиями, обычно не должны кешироваться.
не может получить ответ вовремя.
поддерживается сервером.
- 400 Bad Request
- 403 Forbidden
- 404 Not Found
- 405 Method Not Allowed
- 406 Not Acceptable
- 409 Conflict
- 410 Gone
- 413 Payload Too Large
- 415 Unsupported Media Type
- 422 Unprocessable Entity
- 429 Too Many Requests
- The status of verifying the right to manage the site (ApiVerificationState)
- Rights verification methods (ApiVerificationType)
- Explicit methods of rights verification (ApiExplicitVerificationType)
- Reasons for refusal to verify site management rights (ApiVerificationFailReason)
- Source of the Sitemap file (ApiSitemapSource)
- Type of Sitemap file (ApiSitemapType)
- Site indexing status (ApiHostDataStatus)
- Indexing indicators (ApiIndexingIndicator)
- Query indicators (ApiQueryIndicator)
- Query sorting order (ApiQueryOrderField)
- Device type indicators (ApiDeviceTypeIndicator)
- Indicators of external links (ApiExternalLinksIndicator)
- Internal link indicators (ApiInternalLinksBrokenIndicator)
- Reindexing request status (RecrawlStatusEnum)
- Issue categories on the site (SiteProblemSeverityEnum)
- State of the issue (ApiSiteProblemState)
- Type of site issue (ApiSiteProblemTypeEnum)
- HTTP status codes received by the robot during indexing (IndexingStatusEnum)
- Site page status in search results (ApiSearchEventEnum)
- Changes to important pages in the search (ApiImportantUrlChangeIndicator)
- Reasons for excluding the page from search results (ApiExcludedUrlStatus)
- RSS feed upload modes (PagesLoadMode)
- RSS feed upload mode filter (TaskTypeFilter)
- Status of the RSS feed upload task (LoadStatus)
ENTITY_VALIDATION_ERROR
The request body validation failed.
{
"error_code": "ENTITY_VALIDATION_ERROR",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
FIELD_VALIDATION_ERROR
Invalid parameter passed.
{
"error_code": "FIELD_VALIDATION_ERROR",
"error_message": "explicit error message",
"field_name": "some string",
"field_value": "some string",
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
field_name |
Field. |
field_value |
Value. |
error_message |
Error message. |
INVALID_URL
Wrong URL was passed.
{
"error_code": "INVALID_URL",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
ACCESS_FORBIDDEN
The action is unavailable because the application doesn’t have the necessary permissions.
{
"error_code": "ACCESS_FORBIDDEN",
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
INVALID_OAUTH_TOKEN
The OAuth token is missing or invalid.
{
"error_code": "INVALID_OAUTH_TOKEN",
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
INVALID_USER_ID
The ID of the user who issued the token differs from the one specified in the request. In the examples below, {user_id}
shows the correct uid of the OAuth token owner.
{
"error_code": "INVALID_USER_ID",
"available_user_id": 1,
"error_message": "Invalid user id. {user_id} should be used."
}
Parameter | Description |
---|---|
error_code |
Error code. |
available_user_id |
ID of the user who allowed access. |
error_message |
Error message. |
LICENCE_NOT_ACCEPTED
You have to accept the User agreement.
{
"error_code": "LICENCE_NOT_ACCEPTED",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
HOSTS_LIMIT_EXCEEDED
The number of sites in the user’s site list exceeded the limit (the current limit is 1703).
{
"error_code": "HOSTS_LIMIT_EXCEEDED",
"limit": 1,
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
limit |
The limit on the number of added sites. |
error_message |
Error message. |
RESOURCE_NOT_FOUND
The resource at the requested path does not exist.
{
"error_code": "RESOURCE_NOT_FOUND",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
HOST_NOT_INDEXED
The site isn’t indexed yet.
{
"error_code": "HOST_NOT_INDEXED", //errorCode.
"host_id": "http:ya.ru:80", //id хоста. host id.
"error_message": "some string" //Error message.
}
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
ID of the requested site. |
error_message |
Error message. |
HOST_NOT_LOADED
The site data isn’t uploaded to Yandex.Webmaster yet.
{
"error_code": "HOST_NOT_LOADED",
"host_id": "http:ya.ru:80",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
ID of the requested site. |
error_message |
Error message. |
HOST_NOT_VERIFIED
Site management rights are not verified.
{
"error_code": "HOST_NOT_VERIFIED",
"host_id": "http:ya.ru:80",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
ID of the requested site. |
error_message |
Error message. |
HOST_NOT_FOUND
The site is not in the list of the user’s sites.
{
"error_code": "HOST_NOT_FOUND",
"host_id": "http:ya.ru:80",
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
ID of the requested site. |
error_message |
Error message. |
SITEMAP_NOT_FOUND
The Sitemap for the site wasn’t found.
{
"error_code": "SITEMAP_NOT_FOUND",
"host_id": "http:ya.ru:80",
"sitemap_id": "c7-fe:80-c0",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
ID of the requested site. |
sitemap_id |
The Sitemap file ID. |
error_message |
Error message. |
SITEMAP_NOT_ADDED
The Sitemap file is missing.
{
"error_code": "SITEMAP_NOT_ADDED",
"host_id": "http:ya.ru:80",
"sitemap_id": "c7-fe:80-c0",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
ID of the requested site. |
sitemap_id |
The Sitemap file ID. |
error_message |
Error message. |
TASK_NOT_FOUND
Failed to find a task with the specified ID.
{
"error_code": "TASK_NOT_FOUND",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
QUERY_ID_NOT_FOUND
The specified search query ID does not exist.
{
"error_code": "QUERY_ID_NOT_FOUND",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
The HTTP method is not supported for this resource.
{
"error_code": "METHOD_NOT_ALLOWED",
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
The content types passed in the Accept header are not supported.
{
"error_code": "CONTENT_TYPE_UNSUPPORTED",
"acceptable_types": [
"some string", ...
],
"error_message": "explicit error message"
}
Parameter | Description |
---|---|
error_code |
Error code. |
acceptable_type |
List of supported content types. |
error_message |
Error message. |
URL_ALREADY_ADDED
The URL was already added for reindexing.
{
"error_code": "URL_ALREADY_ADDED",
"error_message": "some string"
}
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
HOST_ALREADY_ADDED
The site with the specified address is already added to the user’s sites list.
{
"error_code": "HOST_ALREADY_ADDED",
"host_id": "http:ya.ru:80",
"verified": false,
"error_message": "some string"
}
<Data>
<error_code>HOST_ALREADY_ADDED</error_code>
<host_id>http:ya.ru:80</host_id>
<verified>false</verified>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
host_id |
The site ID. |
verified |
Indicates if the site rights are verified. |
error_message |
Error message. |
VERIFICATION_ALREADY_IN_PROGRESS
The rights verification process is in progress.
{
"error_code": "VERIFICATION_ALREADY_IN_PROGRESS",
"verification_type": "META_TAG",
"error_message": "some string"
}
<Data>
<error_code>VERIFICATION_ALREADY_IN_PROGRESS</error_code>
<verification_type>META_TAG</verification_type>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
verification_type |
The verification method being processed ( ApiExplicitVerificationType ). |
error_message |
Error message. |
TEXT_ALREADY_ADDED
The text you added earlier.
{
"error_code": "TEXT_ALREADY_ADDED",
"error_message": "some string"
}
<Data>
<error_code>TEXT_ALREADY_ADDED</error_code>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
SITEMAP_ALREADY_ADDED
The Sitemap was already added.
{
"error_code": "SITEMAP_ALREADY_ADDED",
"sitemap_id": "c7-fe:80-c0",
"error_message": "some string"
}
<Data>
<error_code>SITEMAP_ALREADY_ADDED</error_code>
<sitemap_id>c7-fe:80-c0</sitemap_id>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
sitemap_id |
The Sitemap file ID. |
error_message |
Error message. |
Resource unavailable
{
"error_code": "UPLOAD_ADDRESS_EXPIRED",
"valid_until": "2016-01-01T00:00:00,000+0300",
"error_message": "some string"
}
<Data>
<error_code>UPLOAD_ADDRESS_EXPIRED</error_code>
<valid_until>2016-01-01T00:00:00,000+0300</valid_until>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
valid_until |
The date and time until which the URL for task creation is available. |
error_message |
Error message. |
The file size exceeds the limits.
{
"error_code": "REQUEST_ENTITY_TOO_LARGE",
"error_message": "some string"
}
<Data>
<error_code>REQUEST_ENTITY_TOO_LARGE</error_code>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
error_message |
Error message. |
CONTENT_TYPE_UNSUPPORTED
The content type in the request is not supported.
{
"error_code": "CONTENT_TYPE_UNSUPPORTED",
"supported_content_types": [
"some string", ...
],
"error_message": "explicit error message"
}
<Data>
<error_code>CONTENT_TYPE_UNSUPPORTED</error_code>
<supported_content_type>some string</supported_content_type>
...
<error_message>explicit error message</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
supported_content_type |
List of supported content types. |
error_message |
Error message. |
CONTENT_ENCODING_UNSUPPORTED
The request encoding type is not supported.
{
"error_code": "CONTENT_ENCODING_UNSUPPORTED",
"supported_content_encodings": [
"some string"
],
"error_message": "some string"
}
<Data>
<error_code>CONTENT_ENCODING_UNSUPPORTED</error_code>
<supported_content_encoding>some string</supported_content_encoding>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
supported_content_encoding |
List of supported encoding types. |
error_message |
Error message. |
The passed text is too short or too long.
{
"error_code": "TEXT_LENGTH_CONSTRAINTS_VIOLATION",
"max_length": 1,
"min_length": 1,
"actual_length": 1,
"error_message": "explicit error message"
}
<Data>
<error_code>TEXT_LENGTH_CONSTRAINTS_VIOLATION</error_code>
<max_length>1</max_length>
<min_length>1</min_length>
<actual_length>1</actual_length>
<error_message>explicit error message</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
max_length |
Maximum length. |
min_length |
Minimum length. |
actual_length |
The length of the text in the request. |
error_message |
Error message. |
QUOTA_EXCEEDED
The daily quota for requests was exceeded.
{
"error_code": "QUOTA_EXCEEDED",
"daily_quota": 1,
"exceeded_until": "2016-01-01T00:00:00,000+0300",
"error_message": "some string"
}
<Data>
<error_code>QUOTA_EXCEEDED</error_code>
<daily_quota>1</daily_quota>
<exceeded_until>2016-01-01T00:00:00,000+0300</exceeded_until>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
daily_quota |
The maximum number of requests per day. |
exceeded_until |
Time when the new quota starts. |
error_message |
Error message. |
TOO_MANY_REQUESTS_ERROR
Too many requests sent.
{
"error_code": "TOO_MANY_REQUESTS_ERROR",
"daily_quota": 1,
"exceeded_until": "2016-01-01T00:00:00,000+0300",
"error_message": "some string"
}
<Data>
<error_code>TOO_MANY_REQUESTS_ERROR</error_code>
<daily_quota>1</daily_quota>
<exceeded_until>2016-01-01T00:00:00,000+0300</exceeded_until>
<error_message>some string</error_message>
</Data>
Parameter | Description |
---|---|
error_code |
Error code. |
daily_quota |
The maximum number of requests per day. |
exceeded_until |
Time when the new quota starts. |
error_message |
Error message. |
Status | Description |
---|---|
NONE | Verification wasn’t completed and rights are not confirmed. |
VERIFIED | The rights are verified. |
IN_PROGRESS | The rights verification is in progress. |
VERIFICATION_FAILED | Verification was performed but rights are not confirmed. |
INTERNAL_ERROR | An unexpected error occurred when verifying the rights. |
Verification method | Whether a verification check can be requested | Description |
---|---|---|
AUTO | No | Automatic rights verification (deprecated; only for *.narod.ru sites). |
DELEGATED | No | Rights were delegated. |
DNS | Yes | Verifying rights with the DNS record. |
HTML_FILE | Yes | Placing an HTML file in the site’s root directory. |
META_TAG | Yes | Adding a meta tag to the site’s home page header. |
PDD | No | Rights verification via Yandex.Mail for Domains. |
TXT_FILE | No | Placing a text file in the site’s root directory. |
WHOIS | Yes |
Verifying data with information provided by the WHOIS service. This method works only for second-level domains (such as example.com). |
Verification method | Whether a verification check can be requested | Description |
---|---|---|
DNS | Yes | Verifying rights with the DNS record. |
HTML_FILE | Yes | Placing an HTML file in the site’s root directory. |
META_TAG | Yes | Adding a meta tag to the site’s home page header. |
WHOIS | Yes |
Verifying data with information provided by the WHOIS service. This method works only for second-level domains (such as example.com). |
Reason for refusal | Description |
---|---|
DELEGATION CANCELLED | Delegation of site management rights was canceled. |
DNS_RECORD_NOT_FOUND | The specified DNS record doesn’t exist. |
META_TAG_NOT_FOUND | The meta tag is missing in the site’s home page header. |
PDD_VERIFICATION_CANCELLED | Verification of site management rights via Yandex.Mail for Domain isn’t allowed for this site. |
WHOIS_EMAIL_NOT_FOUND | The specified email address is missing in the WHOIS record for this site. |
WRONG_HTML_PAGE_CONTENT | The HTML file content is set incorrectly. |
Source | Description |
---|---|
ROBOTS_TXT | Sitemap is specified in the site’s robots.txt file. |
WEBMASTER | The user added the Sitemap in Yandex.Webmaster. |
INDEX_SITEMAP | Sitemap found in another (index) Sitemap file. |
Type | Description |
---|---|
SITEMAP | Normal Sitemap file that contains the URLs of site pages. |
INDEX_SITEMAP | The Sitemap index file that contains the URLs of other Sitemap files. |
Source | Description |
---|---|
NOT_INDEXED | The site isn’t indexed yet. |
NOT_LOADED | The site data isn’t uploaded to Yandex.Webmaster yet. |
OK | The site is indexed. The data is available in Yandex.Webmaster. |
Indicator | Description |
---|---|
SEARCHABLE | Pages in the search. |
DOWNLOADED | Downloaded pages. |
DOWNLOADED_2XX | Pages downloaded with a 2XX code. |
DOWNLOADED_3XX | Pages downloaded with a 3XX code. |
DOWNLOADED_4XX | Pages downloaded with a 4XX code. |
DOWNLOADED_5XX | Pages downloaded with a 5XX code. |
FAILED_TO_DOWNLOAD | Failed to download. |
EXCLUDED | Excluded pages. |
EXCLUDED_DISALLOWED_BY_USER | Excluded at the request of the resource owner (4XX codes or prohibited in robots.txt). |
EXCLUDED_SITE_ERROR | Excluded due to a site error. |
EXCLUDED_NOT_SUPPORTED | Excluded as not supported by the Yandex robots. |
Indicator | Description |
---|---|
TOTAL_SHOWS | The number of displays. |
TOTAL_CLICKS | The number of clicks. |
AVG_SHOW_POSITION | The average position of the display. |
AVG_CLICK_POSITION | Average click position. |
Indicator | Description |
---|---|
TOTAL_SHOWS | The number of displays. |
TOTAL_CLICKS | The number of clicks. |
Indicator | Description |
---|---|
ALL | All device types. |
DESKTOP | Computers. |
MOBILE_AND_TABLET | Mobile phones and tablets. |
MOBILE | Mobile phones. |
TABLET | Tablets. |
If the request does not specify a device type indicator, the default value is ALL.
Indicator | Description |
---|---|
LINKS_TOTAL_COUNT | The total number of known external links to the host. |
Indicator | Description |
---|---|
SITE_ERROR | The total number of known external links to the site. |
DISALLOWED_BY_USER | The page doesn’t exist or is prohibited from indexing. |
UNSUPPORTED_BY_ROBOT | Not supported by the main Search indexing robot. |
Indicator | Description |
---|---|
IN_PROGRESS | The request is being processed. |
DONE | The robot crawled the URL |
FAILED | The robot failed to crawl the page. Make sure it is accessible to the robot and the server responds fast enough. |
Indicator | Description | Note |
---|---|---|
FATAL | Fatal errors. Checks the server connection, site availability for indexing, security and compliance with Yandex guidelines. |
This may lead to excluding individual pages or the entire site from search results. We recommend monitoring these errors and fixing them as soon as possible. |
CRITICAL | Critical issues. Checks the presence and validity of the SSL certificate, the number of broken internal links, and the server response time. | |
POSSIBLE_PROBLEM | Possible issues. Checks the Sitemap and robots.txt file validity, settings for displaying non-existent files, the number of duplicate pages, the presence of redirects, annoying ads, and so on. | May affect the quality and speed of site indexing. |
RECOMMENDATION | Recommendations. Usually includes suggestions for improving the site’s ranking in search results. | Use them to improve the site’s ranking in search results. |
Indicator | Description |
---|---|
PRESENT | Present on the site. |
ABSENT | Missing. |
UNDEFINED | Not enough data to determine if there are issues. |
Indicator | Description |
---|---|
FATAL | |
DISALLOWED_IN_ROBOTS | The site is prohibited for indexing in the robots.txt file. |
DNS_ERROR | Failed to connect to the server due to a DNS error. |
MAIN_PAGE_ERROR | The site’s home page returns an error. |
THREATS | Security threats or issues were detected. |
CRITICAL | |
SLOW_AVG_RESPONSE_TIME | Slow server response. For more information, see this Help section. |
SSL_CERTIFICATE_ERROR | Invalid SSL certificate settings. For more information, see this Help section. |
POSSIBLE_PROBLEM | |
BAD_ADVERTISEMENT | Ad formats do not comply with IAB Russia recommendations. |
DOCUMENTS_MISSING_DESCRIPTION | Many pages do not have the Description meta tag. |
DOCUMENTS_MISSING_TITLE | The title element is missing on many pages. |
ERROR_IN_ROBOTS_TXT | Errors in the robots.txt file. |
ERRORS_IN_SITEMAPS | Errors found in the Sitemap file. |
MAIN_MIRROR_IS_NOT_HTTPS | The site’s main mirror doesn’t use the HTTPS protocol We recommend using the HTTPS protocol. For more information and instructions on switching protocols, see the Help. |
MAIN_PAGE_REDIRECTS | The main page redirects to another site. |
NO_METRIKA_COUNTER_CRAWL_ENABLED | Site crawling using Yandex.Metrica tags isn’t enabled. For more information about site indexing using the Yandex.Metrica tag, see the Help. |
NO_ROBOTS_TXT | The robots.txt file wasn’t found. |
NO_SITEMAPS | The Sitemap files used by the robot are missing. |
NO_SITEMAP_MODIFICATIONS | The Sitemap files haven’t been updated for a long time. |
NON_WORKING_VIDEO | The robot failed to index videos on the site. |
SOFT_404 | The display of non-existent files and pages is configured incorrectly. |
TOO_MANY_DOMAINS_ON_SEARCH | The site subdomains are found in the search results. |
TOO_MANY_PAGE_DUPLICATES | Too many duplicate pages. |
RECOMMENDATION | |
FAVICON_PROBLEM | The favicon file was not found. The robot failed to load an image file to display in the browser tab and next to the site name in the search results. For more information about this error and how to fix it, see the help section. |
INCOMPLETE_SPRAV_COMPANY_PROFILE | Yandex.Directory contains incomplete information about the organization. |
NO_CHATS | Chats on Search are missing. |
NO_METRIKA_COUNTER | Yandex.Metrica tag error |
NO_REGIONS | The site region isn’t set. |
NOT_IN_SPRAV | The site isn’t registered in Yandex.Directory. |
NOT_MOBILE_FRIENDLY | The site isn’t optimized for mobile devices. |
Indicator | Description |
---|---|
HTTP_2XX HTTP_3XX HTTP_4XX HTTP_5XX |
For more information about statuses, see the help section. |
OTHER | Unsupported HTTP code, connection error, or other error. |
Indicator | Description |
---|---|
APPEARED_IN_SEARCH | The page appeared in search results. |
REMOVED_FROM_SEARCH | The page was removed from search results. |
Indicator | Description |
---|---|
INDEXING_HTTP_CODE | The HTTP response code received by the robot when crawling the page changed. |
SEARCH_STATUS | The page status in the search changed (it was added or removed). |
TITLE | The page title changed. |
DESCRIPTION | The Description meta tag content changed. |
Indicator | Description |
---|---|
NOTHING_FOUND | The robot doesn’t know about the page, or it was unavailable for a long time. Submit the page for reindexing. |
HOST_ERROR | When trying to access the site, the robot could not connect to the server. Check the server response and make sure that the Yandex robot isn’t blocked by the hosting provider. The site is indexed automatically when it becomes available for the robot. For information about the user agent robots, see the help section. |
REDIRECT_NOTSEARCHABLE | The page redirects to another page. The target page is indexed (RedirectTarget). Check the indexing of the target page. |
HTTP_ERROR | An error occurred when accessing the “HTTP error” page. Check the server response. If the problem persists, contact your site administrator or the server administrator. If the page is already available, submit it for reindexing. |
NOT_CANONICAL | The page is indexed by the canonical URL specified in the rel=»canonical» attribute in its source code. Correct or delete the attribute if it is specified incorrectly. The robot will track the changes automatically. |
NOT_MAIN_MIRROR | The page belongs to a secondary site mirror, so it was excluded from the search. |
PARSER_ERROR | When trying to access the page, the robot couldn’t get its content. Check the server response or the presence of prohibiting HTML elements. If the problem persists, contact your site administrator or the server administrator. If the page is already available, send it for reindexing. |
ROBOTS_HOST_ERROR | Site indexing is prohibited in the robots.txt file. The robot will automatically start crawling the page when the site becomes available for indexing. |
ROBOTS_URL_ERROR | Page indexing is prohibited in the robots.txt file. The robot will automatically crawl the page when it becomes available for indexing. |
DUPLICATE | The page duplicates a site page that is already in the search. For more information, see the help section. |
LOW_QUALITY | The page has been removed from search results due to low quality as determined by a special algorithm. If the algorithm finds the page relevant to users’ search queries, it will appear in the search automatically. |
CLEAN_PARAMS | The page was excluded from the search after the robot processed the Clean-param directive. To get the page indexed, edit the robots.txt file. |
NO_INDEX | The page is excluded because the robots meta tag has the noindex value. |
OTHER |
The robot does not have updated data for the page. Check the server response or the presence of prohibiting HTML elements. If the page can’t be accessed by the robot, contact the administrator of your site or server. If the page is already available, send it for reindexing. |
Indicator | Description |
---|---|
DEBUG | Debugging the Turbo page display. |
PRODUCTION | Turbo pages publishing. |
Indicator | Description |
---|---|
DEBUG | Debugging the Turbo page display. |
PRODUCTION | Turbo pages publishing. |
ALL | Getting information about both task types. |
Indicator | Description |
---|---|
PROCESSING | The file is checked for errors. |
OK | The file is loaded and it doesn’t contain errors. |
WARNING | XML elements in the file aren’t supported by Yandex or are specified incorrectly. |
ERROR | The file contains errors (for example, duplicate XML elements). |
Error codes are almost the last thing that you want to see in an API response. Generally speaking, it means one of two things — something was so wrong in your request or your handling that the API simply couldn’t parse the passed data, or the API itself has so many problems that even the most well-formed request is going to fail. In either situation, traffic comes crashing to a halt, and the process of discovering the cause and solution begins.
That being said, errors, whether in code form or simple error response, are a bit like getting a shot — unpleasant, but incredibly useful. Error codes are probably the most useful diagnostic element in the API space, and this is surprising, given how little attention we often pay them.
Today, we’re going to talk about exactly why error responses and handling approaches are so useful and important. We’ll take a look at some common error code classifications the average user will encounter, as well as some examples of these codes in action. We’ll also talk a bit about what makes a “good” error code and what makes a “bad” error code, and how to ensure your error codes are up to snuff.
The Value of Error Codes
As we’ve already said, error codes are extremely useful. Error codes in the response stage of an API is the fundamental way in which a developer can communicate failure to a user. This stage, sitting after the initial request stage, is a direct communication between client and API. It’s often the first and most important step towards not only notifying the user of a failure, but jump-starting the error resolution process.
A user doesn’t choose when an error is generated, or what error it gets — error situations often arise in instances that, to the user, are entirely random and suspect. Error responses thus are the only truly constant, consistent communication the user can depend on when an error has occurred. Error codes have an implied value in the way that they both clarify the situation, and communicate the intended functionality.
Consider for instance an error code such as “401 Unauthorized – Please Pass Token.” In such a response, you understand the point of failure, specifically that the user is unauthorized. Additionally, however, you discover the intended functionality — the API requires a token, and that token must be passed as part of the request in order to gain authorization.
With a simple error code and resolution explanation, you’ve not only communicated the cause of the error, but the intended functionality and method to fix said error — that’s incredibly valuable, especially for the amount of data that is actually returned.
HTTP Status Codes
Before we dive deeper into error codes and what makes a “good” code “good,” we need to address the HTTP Status Codes format. These codes are the most common status codes that the average user will encounter, not just in terms of APIs but in terms of general internet usage. While other protocols exist and have their own system of codes, the HTTP Status Codes dominate API communication, and vendor-specific codes are likely to be derived from these ranges.
1XX – Informational
The 1XX range has two basic functionalities. The first is in the transfer of information pertaining to the protocol state of the connected devices — for instance, 101 Switching Protocols
is a status code that notes the client has requested a protocol change from the server, and that the request has been approved. The 1XX range also clarifies the state of the initial request. 100 Continue
, for instance, notes that a server has received request headers from a client, and that the server is awaiting the request body.
2XX – Success
The 2XX range notes a range of successes in communication, and packages several responses into specific codes. The first three status codes perfectly demonstrate this range – 200 OK
means that a GET or POST request was successful, 201 Created
confirms that a request has been fulfilled and a new resource has been created for the client, and 202 Accepted
means that the request has been accepted, and that processing has begun.
3XX – Redirection
The 3XX range is all about the status of the resource or endpoint. When this type of status code is sent, it means that the server is still accepting communication, but that the point contacted is not the correct point of entry into the system. 301 Moved Permanently
verifies that the client request did in fact reach the correct system, but that this request and all future requests should be handled by a different URI. This is very useful in subdomains and when moving a resource from one server to another.
4XX – Client Error
The 4XX series of error codes is perhaps the most famous due to the iconic 404 Not Found
status, which is a well-known marker for URLs and URIs that are incorrectly formed. Other more useful status codes for APIs exist in this range, however.
414 URI Too Long
is a common status code, denoting that the data pushed through in a GET request is too long, and should be converted to a POST request. Another common code is 429 Too many Requests
, which is used for rate limiting to note a client is attempting too many requests at once, and that their traffic is being rejected.
5XX – Server Error
Finally the 5XX range is reserved for error codes specifically related to the server functionality. Whereas the 4XX range is the client’s responsibility (and thus denotes a client failure), the 5XX range specifically notes failures with the server. Error codes like 502 Bad Gateway
, which notes the upstream server has failed and that the current server is a gateway, further expose server functionality as a means of showing where failure is occurring. There are less specific, general failures as well, such as 503 Service Unavailable
.
Making a Good Error Code
With a solid understanding of HTTP Status Codes, we can start to dissect what actually makes for a good error code, and what makes for a bad error code. Quality error codes not only communicate what went wrong, but why it went wrong.
Overly opaque error codes are extremely unhelpful. Let’s imagine that you are attempting to make a GET request to an API that handles digital music inventory. You’ve submitted your request to an API that you know routinely accepts your traffic, you’ve passed the correct authorization and authentication credentials, and to the best of your knowledge, the server is ready to respond.
You send your data, and receive the following error code – 400 Bad Request
. With no additional data, no further information, what does this actually tell you? It’s in the 4XX range, so you know the problem was on the client side, but it does absolutely nothing to communicate the issue itself other than “bad request.”
This is when a “functional” error code is really not as functional as it should be. That same response could easily be made helpful and transparent with minimal effort — but what would this entail? Good error codes must pass three basic criteria in order to truly be helpful. A quality error code should include:
- An HTTP Status Code, so that the source and realm of the problem can be ascertained with ease;
- An Internal Reference ID for documentation-specific notation of errors. In some cases, this can replace the HTTP Status Code, as long as the internal reference sheet includes the HTTP Status Code scheme or similar reference material.
- Human readable messages that summarize the context, cause, and general solution for the error at hand.
Include Standardized Status Codes
First and foremost, every single error code generated should have an attached status code. While this often takes the form of an internal code, it typically takes the form of a standardized status code in the HTTP Status Code scheme. By noting the status using this very specific standardization, you not only communicate the type of error, you communicate where that error has occurred.
There are certain implications for each of the HTTP Status Code ranges, and these implications give a sense as to the responsibility for said error. 5XX errors, for instance, note that the error is generated from the server, and that the fix is necessarily something to do with server-related data, addressing, etc. 4XX, conversely, notes the problem is with the client, and specifically the request from the client or the status of the client at that moment.
By addressing error codes using a default status, you can give a very useful starting point for even basic users to troubleshoot their errors.
Give Context
First and foremost, an error code must give context. In our example above, 400 Bad Request
means nothing. Instead, an error code should give further context. One such way of doing this is by passing this information in the body of the response in the language that is common to the request itself.
For instance, our error code of 400 Bad Request
can easily have a JSON body that gives far more useful information to the client:
< HTTP/1.1 400 Bad Request
< Date: Wed, 31 May 2017 19:01:41 GMT
< Server: Apache/2.4.25 (Ubuntu)
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: application/json
{ "error" : "REQUEST - BR0x0071" }
This error code is good, but not great. What does it get right? Well, it supplies context, for starters. Being able to see what the specific type of failure is shows where the user can begin the problem solving process. Additionally, and vitally, it also gives an internal reference ID in the form of “BR0x0071”, which can be internally referenced.
While this is an ok error code, it only meets a fraction of our requirements.
Human Readability
Part of what makes error codes like the one we just created so powerful is that it’s usable by humans and machines alike. Unfortunately, this is a very easy thing to mess up — error codes are typically handled by machines, and so it’s very tempting to simply code for the application rather than for the user of said application.
In our newly formed example, we have a very clear error to handle, but we have an additional issue. While we’ve added context, that context is in the form of machine-readable reference code to an internal error note. The user would have to find the documentation, look up the request code “BRx0071”, and then figure out what went wrong.
We’ve fallen into that trap of coding for the machine. While our code is succinct and is serviceable insomuch as it provides context, it does so at the cost of human readability. With a few tweaks, we could improve the code, while still providing the reference number as we did before:
< HTTP/1.1 400 Bad Request
< Date: Wed, 31 May 2017 19:01:41 GMT
< Server: Apache/2.4.25 (Ubuntu)
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: application/json
{ "error" : "Bad Request - Your request is missing parameters. Please verify and resubmit. Issue Reference Number BR0x0071" }
With such a response, not only do you get the status code, you also get useful, actionable information. In this case, it tells the user the issue lies within their parameters. This at least offers a place to start troubleshooting, and is far more useful than saying “there’s a problem.”
While you still want to provide the issue reference number, especially if you intend on integrating an issue tracker into your development cycle, the actual error itself is much more powerful, and much more effective than simply shooting a bunch of data at the application user and hoping something sticks.
Good Error Examples
Let’s take a look at some awesome error code implementations on some popular systems.
Twitter API is a great example of descriptive error reporting codes. Let’s attempt to send a GET request to retrieve our mentions timeline.
https://api.twitter.com/1.1/statuses/mentions_timeline.json
When this is sent to the Twitter API, we receive the following response:
HTTP/1.1 400 Bad Request
x-connection-hash:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
set-cookie:
guest_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Date:
Thu, 01 Jun 2017 03:04:23 GMT
Content-Length:
62
x-response-time:
5
strict-transport-security:
max-age=631138519
Connection:
keep-alive
Content-Type:
application/json; charset=utf-8
Server:
tsa_b
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
Looking at this data, we can generally figure out what our issue is. First, we’re told that we’ve submitted a 400 Bad Request
. This tells us that the problem is somewhere in our request. Our content length is acceptable, and our response time is well within normal limits. We can see, however, that we’re receiving a unique error code that Twitter itself has denoted — “215”, with an attached message that states “Bad Authentication data”.
This error code supplies both valuable information as to why the error has occurred, and also how to rectify it. Our error lies in the fact that we did not pass any authentication data whatsoever — accordingly, error 215 is referenced, which tells us the fix is to supply said authentication data, but also gives us a number to reference on the internal documentation of the Twitter API.
For another great example, let’s look at another social network. Facebook’s Graph API allows us to do quite a lot as long as we have the proper authentication data. For the purposes of this article, all personal information will be blanked out for security purposes.
First, let’s pass a GET request to ascertain some details about a user:
https://graph.facebook.com/v2.9/me?fields=id%2Cname%2Cpicture%2C%20picture&access_token=xxxxxxxxxxx
This request should give us a few basic fields from this user’s Facebook profile, including id, name, and picture. Instead, we get this error response:
{
"error": {
"message": "Syntax error "Field picture specified more than once. This is only possible before version 2.1" at character 23: id,name,picture,picture",
"type": "OAuthException",
"code": 2500,
"fbtrace_id": "xxxxxxxxxxx"
}
}
While Facebook doesn’t directly pass the HTTP error code in the body, it does pass a lot of useful information. The “message” area notes that we’ve run into a syntax error, specifically that we’ve defined the “picture” field more than once. Additionally, this field lets us know that this behavior was possible in previous versions, which is a very useful tool to communicate to users a change in behavior from previous versions to the current.
Additionally, we are provided both a code and an fbtrace_id
that can be used with support to identify specific issues in more complex cases. We’ve also received a specific error type, in this case OAuthException
, which can be used to narrow down the specifics of the case even further.
Bing
To show a complex failure response code, let’s send a poorly formed (essentially null) GET request to Bing.
HTTP/1.1 200
Date:
Thu, 01 Jun 2017 03:40:55 GMT
Content-Length:
276
Connection:
keep-alive
Content-Type:
application/json; charset=utf-8
Server:
Microsoft-IIS/10.0
X-Content-Type-Options:
nosniff
{"SearchResponse":{"Version":"2.2","Query":{"SearchTerms":"api error codes"},"Errors":[{"Code":1001,"Message":"Required parameter is missing.","Parameter":"SearchRequest.AppId","HelpUrl":"httpu003au002fu002fmsdn.microsoft.comu002fen-usu002flibraryu002fdd251042.aspx"}]}}
This is a very good error code, perhaps the best of the three we’ve demonstrated here. While we have the error code in the form of “1001”, we also have a message stating that a parameter is missing. This parameter is then specifically noted as “SearchRequestAppId”, and a “HelpUrl” variable is passed as a link to a solution.
In this case, we’ve got the best of all worlds. We have a machine readable error code, a human readable summary, and a direct explanation of both the error itself and where to find more information about the error.
Spotify
Though 5XX errors are somewhat rare in modern production environments, we do have some examples in bug reporting systems. One such report noted a 5XX error generated from the following call:
GET /v1/me/player/currently-playing
This resulted in the following error:
[2017-05-02 13:32:14] production.ERROR: GuzzleHttpExceptionServerException: Server error: `GET https://api.spotify.com/v1/me/player/currently-playing` resulted in a `502 Bad Gateway` response:
{
"error" : {
"status" : 502,
"message" : "Bad gateway."
}
}
So what makes this a good error code? While the 502 Bad gateway error seems opaque, the additional data in the header response is where our value is derived. By noting the error occurring in production and its addressed variable, we get a general sense that the issue at hand is one of the server gateway handling an exception rather than anything external to the server. In other words, we know the request entered the system, but was rejected for an internal issue at that specific exception address.
When addressing this issue, it was noted that 502 errors are not abnormal, suggesting this to be an issue with server load or gateway timeouts. In such a case, it’s almost impossible to note granularly all of the possible variables — given that situation, this error code is about the best you could possibly ask for.
Conclusion
Much of an error code structure is stylistic. How you reference links, what error code you generate, and how to display those codes is subject to change from company to company. However, there has been headway to standardize these approaches; the IETF recently published RFC 7807, which outlines how to use a JSON object as way to model problem details within HTTP response. The idea is that by providing more specific machine-readable messages with an error response, the API clients can react to errors more effectively.
In general, the goal with error responses is to create a source of information to not only inform the user of a problem, but of the solution to that problem as well. Simply stating a problem does nothing to fix it – and the same is true of API failures.
The balance then is one of usability and brevity. Being able to fully describe the issue at hand and present a usable solution needs to be balanced with ease of readability and parsability. When that perfect balance is struck, something truly powerful happens.
While it might seem strange to wax philosophically about error codes, they are a truly powerful tool that go largely underutilized. Incorporating them in your code is not just a good thing for business and API developer experience – they can lead to more positive end user experience, driving continuous adoption and usage.
Chapter 6
The curl
requests we have used so far have all been expertly crafted to work. We haven’t tried to game the API or make it fail, because we are nice people.
Not everyone is like this, unfortunately! And it’s not only people with bad intentions we need to look out for, but also simple mistakes. Anyone can make a mistake — it happens. That does not mean we should laugh at them for trying and send back some indecipherable message.
Descriptive messages are a very important part of any web API. Web APIs are used by our fellow developers and, by building an API, we take the responsibility of providing a good service for them. Any service should be easy to use. Put yourself inside a user’s shoes and pinpoint the issues someone could have with your service.
The obvious problem in our current web API is that we don’t send back meaningful errors when something goes wrong.
Let’s take the following curl
request as an example. Notice anything wrong? We forgot to close the JSON
document. Before we can realize our mistake, we send the request…
curl -i -X POST http://localhost:4567/users -H "Content-Type: application/json" -d '{"first_name":"Samuel", "last_name":"Da Costa", "age":19'
and we end up with a scary 500 Internal Server Error
. This seems to mean that there was something wrong with the server, not with our request.
HTTP/1.1 500 Internal Server Error Content-Type: text/plain Content-Length: 4679 Connection: keep-alive Server: thin [JSON::ParserError]
Luckily, Sinatra sends back the whole stack trace, so we can easily debug it. Not every framework is that nice, though. That’s the server’s duty — to provide descriptive errors to the client. A 500
is as descriptive as looking at a black box that just says: “Sorry bro, it didn’t work”.
HTTP comes with a set of features to handle errors. Indeed, thanks to all its HTTP status codes, we can configure our API to send back descriptive error messages to a client in a format that it can understand.
6.1. The different classes of HTTP status codes
There are five classes of HTTP codes:
1XX
Informational: Status codes starting with1
are known as informational codes. Most of them are rarely used nowadays.2XX
Success: These codes indicate that the exchange between the server and the client was successful.3XX
Redirection:3XX
codes indicate that the client must take additional action before the request can be completed.4XX
Client Error: There was something wrong with the request the client sent and the server cannot process it.5XX
Server Error: The client sent a valid request but the server was not able to process it successfully.
We will be using status codes from some of these classes in this chapter.
6.2. Global
We will add error handling for each route, but let’s first see the errors we need to handle for every request.
6.2.1. 405 Method Not Allowed
This HTTP status code can be used when the client tries to access a resource using an unsupported HTTP method. For example, in our API, what would happen if a client tried to use the PUT
method with the /users
URI?
Let’s give it a try.
curl -i -X PUT http://localhost:4567/users
Output
HTTP/1.1 404 Not Found Content-Type: text/html;charset=utf-8 X-Cascade: pass Content-Length: 467 X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN Connection: keep-alive Server: thin <!DOCTYPE html> <html> <head> <MORE HTML>
That’s not very helpful… Plus, it returns 404
. While we do have a resource living at that URI, it’s not the right HTTP method… we can do better. All we need to do is catch any request accessing /users
with an unsupported method: put
, patch
and delete
. With a bit of metaprogramming, it’s not hard to do.
In the code below, we loop through each of the HTTP methods we don’t support and define a Sinatra route that returns 405 Method Not Allowed
for each one of them.
# webapi.rb # /users # head /users # get /users # post /users [:put, :patch, :delete].each do |method| send(method, '/users') do halt 405 end end # options /users/:first_name
Let’s give it another try after restarting the server, shall we?
curl -i -X PUT http://localhost:4567/users
Output
HTTP/1.1 405 Method Not Allowed Content-Type: text/html;charset=utf-8 Content-Length: 0 [MORE HEADERS]
Alright! It’s working correctly, let’s proceed.
6.2.2. 406 Not Acceptable
We already implemented one HTTP status code in the previous chapters. If the client requests a media type that our API does not support, we will return 406 Not Acceptable
. To the client receiving this, it means that the server was not able to generate a representation for the resource according to the criteria the client had fixed. The response should also include what formats are actually available for the client to pick from.
# webapi.rb # users # ... helpers do # def json_or_default? # def xml? def accepted_media_type return 'json' unless request.accept.any? request.accept.each do |type| return 'json' if json_or_default?(type) return 'xml' if xml?(type) end content_type 'text/plain' halt 406, 'application/json, application/xml' end # def type # def send_data end
Let’s try with a fake media type that we do not support.
curl -i http://localhost:4567/users -H "Accept: moar/curl"
Output
HTTP/1.1 406 Not Acceptable Content-Type: text/plain;charset=utf-8 Content-Length: 33 ... More Headers ... application/json, application/xml
With this, the client can understand what is actually supported and act accordingly. Sadly, it’s not defined more clearly in a standard.
Alternatively, we could actually return a JSON representation instead of telling the client that we can’t give it anything. We would set the Content-Type
header to application/json
to let the client do its own checking before it parses the response. Both this option and the previous one are acceptable as defined in the HTTP RFC.
# webapi.rb # users # ... helpers do # def json_or_default? # def xml? def accepted_media_type return 'json' unless request.accept.any? request.accept.each do |type| return 'json' if json_or_default?(type) return 'xml' if xml?(type) end 'json' end # def type # def send_data end
Don’t forget to restart the server.
curl -i http://localhost:4567/users -H "Accept: moar/curl"
Output
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 203 ... More Headers ... [ {"first_name":"Thibault", "last_name":"Denizet", "age":25, "id":"thibault"}, {"first_name":"Simon", "last_name":"Random", "age":26, "id":"simon"}, {"first_name":"John", "last_name":"Smith", "age":28, "id":"john"} ]
If your server cannot generate a representation the way the client requests, you can either return 406
(with or without a list of actually supported media types), or just return the default format and let the client handle it.
6.3. POST /users
For the post /users
route, we are currently not handling any errors. If you run the following curl
request, it will crash and send you back 500
and the whole stack trace.
curl -X POST -i http://localhost:4567/users -H "Content-Type: application/fake" -d 'Weirdly Formatted Data'
Output
HTTP/1.1 500 Internal Server Error Content-Type: text/plain Content-Length: 4647 Connection: keep-alive Server: thin JSON::ParserError: 757: unexpected token at 'Weirdly Formatted Data' [Stack Trace]
This does not help the client in understanding what happened. It does help us humans, because we can read the Ruby stack trace and see that there was a JSON::ParserError
. But to an automated client, this only means that something went wrong on the server. We need to fix this.
6.3.1. 415 Unsupported Media Type
To fix it we will use the 415
HTTP status code. 415 Unsupported Media Type
is exactly what its name implies — we can return it to the client when we don’t understand the format of the data sent by the client.
To prevent the execution of the code there, we will first check if the data was sent as a JSON document, the only format we support for requests. Our code must be guarded from unwanted media types.
We just need the following line to do it.
halt 415 unless request.env['CONTENT_TYPE'] == 'application/json'
And it comes in the post /users
route like this:
# webapi.rb # Stuff # ... post '/users' do halt 415 unless request.env['CONTENT_TYPE'] == 'application/json' users[user['first_name'].downcase.to_sym] = user url = "http://localhost:4567/users/#{user['first_name']}" response.headers['Location'] = url status 201 end
Don’t forget to restart the server.
Now, let’s see what happens when we send the curl
request seen in the previous section.
curl -X POST -i http://localhost:4567/users -H "Content-Type: application/fake" -d 'Weirdly Formatted Data'
Output
HTTP/1.1 415 Unsupported Media Type [MORE HEADERS]
That’s much more descriptive, right? The only problem is that this does not tell the client which media types are actually supported. We will see what we can do about this later. For now, our endpoint won’t crash anymore whatever the received format is.
6.3.2. 400 Bad Request
The 400 Bad Request
is used way too often in modern web applications. Its real purpose is to indicate that the server could not understand the request due to some syntax issue. For example, a malformed JSON document.
Let’s give it a try and break some stuff.
curl -X POST -i http://localhost:4567/users -H "Content-Type: application/json" -d '{"first_name":"Mark"'
Output
HTTP/1.1 500 Internal Server Error Content-Type: text/plain Content-Length: 4645 Connection: keep-alive Server: thin JSON::ParserError: 757: unexpected token at '{"first_name":"Mark"' [Stack Trace]
Boom! Broken. Since our JSON document, {"first_name":"Mark"
, is not valid, our server crashes when trying to parse it. Here is how we can fix this. We are going to catch the exception raised when parsing an invalid JSON document (JSON::ParserError
). In the rescue
, we will send back the error to the client, in the format of its choice (specified by the Accept
header). Note that we are still using the send_data
method we wrote earlier.
# webapi.rb # Stuff # ... post '/users' do halt 415 unless request.env['CONTENT_TYPE'] == 'application/json' begin user = JSON.parse(request.body.read) rescue JSON::ParserError => e halt 400, send_data(json: -> { { message: e.to_s } }, xml: -> { { message: e.to_s } }) end users[user['first_name'].downcase.to_sym] = user url = "http://localhost:4567/users/#{user['first_name']}" response.headers['Location'] = url status 201 end
Don’t forget to restart your server!
curl -X POST -i http://localhost:4567/users -H "Content-Type: application/json" -d '{"first_name":"Mark"'
Output
HTTP/1.1 400 Bad Request Content-Type: application/json Content-Length: 65 X-Content-Type-Options: nosniff Connection: keep-alive Server: thin {"message":"757: unexpected token at '{"first_name":"Mark"'"}
Great! We are getting a 400
back and the body contains the error message.
6.3.3. 409 Conflict
Currently, if we try to re-create a user that already exists, it’s just going to override the existing one. Not good. This should throw up some kind of conflict error saying that a user cannot be overridden. The problem here is how we save users in a Ruby hash. Since we use the first name as a key, we don’t want to allow the override of an existing user.
Luckily, that’s what the 409 Conflict
HTTP code is for. Note that this code is only allowed in situations where the client can actually fix the conflict. In our case, the client can either change the first name or use another endpoint to update the user.
Our use of the first name as a key is there only for simplicity and any production application should not use such a mechanism. Unique generated IDs are way better!
To prevent any override, we will use this code. If we find a user with the first name sent by the client, we’ll immediately halt and send back a response to the client with a 409
status code and an explanation message.
if users[user['first_name'].downcase.to_sym] message = { message: "User #{user['first_name']} already in DB." } halt 409, send_data(json: -> { message }, xml: -> { message }) end
Here is our full POST
endpoint:
# webapi.rb # Stuff # ... post '/users' do halt 415 unless request.env['CONTENT_TYPE'] == 'application/json' begin user = JSON.parse(request.body.read) rescue JSON::ParserError => e halt 400, send_data(json: -> { { message: e.to_s } }, xml: -> { { message: e.to_s } }) end if users[user['first_name'].downcase.to_sym] message = { message: "User #{user['first_name']} already in DB." } halt 409, send_data(json: -> { message }, xml: -> { message }) end users[user['first_name'].downcase.to_sym] = user url = "http://localhost:4567/users/#{user['first_name']}" response.headers['Location'] = url status 201 end
Let’s try to recreate an existing user (for example, Thibault), after restarting the server.
curl -X POST -i http://localhost:4567/users -H "Content-Type: application/json" -d '{"first_name":"Thibault", "last_name":"Denizet", "age":25}'
Output
HTTP/1.1 409 Conflict Content-Type: application/json Content-Length: 42 X-Content-Type-Options: nosniff Connection: keep-alive Server: thin {"message":"User Thibault already in DB."}
Great, we’re telling the client that its request triggered a conflict that needs to be solved. We can now detect when updates conflict with the users’ data stored in the users
hash.
6.4. GET /users/:first_name
Let’s now turn our attention to the get /users/:first_name
route. We know our endpoint works fine when the user exists. But what happens when it doesn’t?
curl -i http://localhost:4567/users/frank
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 4 ... More Headers ... null
What the heck is this null
doing here? Plus, we are telling the client it’s a JSON document with the Content-Type
. We really need to fix this!
6.4.1. 404 Not Found
The 404 Not Found
status code can help us. This code is meant to tell the client that nothing was found at the URI specified by the client; in other words, the requested resource does not exist.
This fits what we need for the get /users/:first_name
route pretty well. Let’s add a little halt that will return 404
if the user is not found in our hash.
# webapi.rb # Stuff # ... get '/users/:first_name' do |first_name| halt 404 unless users[first_name.to_sym] send_data(json: -> { users[first_name.to_sym].merge(id: first_name) }, xml: -> { { first_name => users[first_name.to_sym] } }) end
Restart the server and send the following request.
curl -i http://localhost:4567/users/frank
Output
HTTP/1.1 404 Not Found
... More Headers ...
Looks good!
6.4.2. 410 Gone
Sadly 404 Not Found
can seem quite generic to a client. We can use other codes to give a more specific response. One of them is 410 Gone
which indicates that a resource used to live at the given URI, but doesn’t anymore. It has probably been deleted since the server does not have the new location.
Currently, if we delete a user and then try to access it, we will just get 404
, as if it never existed.
It’s not always possible for a server to indicate a deleted resource and there is nothing forcing us to use this HTTP status. It is helpful for a client though, since it will let the client know that this URI does not point to anything anymore. It shouldn’t be considered as a bug since there used to be something there. The client should take note that it’s now gone and move on with its life.
Let’s quickly add a mechanism to keep track of what has been deleted. In a production application with a real database, it is possible to achieve this kind of mechanism by using a boolean in order to see if something has been deleted or not. There are other ways to do it, but we won’t be covering them.
The first thing we need is a hash, named deleted_users
, that will contain all the deleted users (duh!).
# webapi.rb # require users = { thibault: { first_name: 'Thibault', last_name: 'Denizet', age: 25 }, simon: { first_name: 'Simon', last_name: 'Random', age: 26 }, john: { first_name: 'John', last_name: 'Smith', age: 28 } } deleted_users = {} # Helpers # Routes
Then we need to update the get /users/:first_name
route to halt with 410
if the deleted_users
hash contains the specified user.
# webapi.rb # stuff get '/users/:first_name' do |first_name| halt 410 if deleted_users[first_name.to_sym] halt 404 unless users[first_name.to_sym] send_data(json: -> { users[first_name.to_sym].merge(id: first_name) }, xml: -> { { first_name => users[first_name.to_sym] } }) end
Finally, we need to fill the deleted_users
hash every time a user gets deleted in the delete /users/:first_name
route.
# webapi.rb # stuff delete '/users/:first_name' do |first_name| first_name = first_name.to_sym deleted_users[first_name] = users[first_name] if users[first_name] users.delete(first_name) status 204 end
Everything is in place now and we can start sending some test requests. First, restart the server. Then delete the simon
user with this command:
curl -i -X DELETE http://localhost:4567/users/simon
Output
HTTP/1.1 204 No Content [ ... ]
Now, what happens when we try to access the Simon resource?
curl -i http://localhost:4567/users/simon
HTTP/1.1 410 Gone Content-Type: text/html;charset=utf-8 Content-Length: 0 [More Headers]
Our little API is getting more expressive by the minute!
6.5. PUT /users/:first_name
For this route, we can handle 415 Unsupported Media Type
and 400 Bad Request
. However, I’m not going to show you how. Instead, I want you to do it.
Testing 415
curl -X PUT -i http://localhost:4567/users/thibault -H "Content-Type: application/fake" -d 'Weirdly Formatted Data'
Testing 400
curl -X PUT -i http://localhost:4567/users/thibault -H "Content-Type: application/json" -d '{"first_name":"Tibo"'
6.6. PATCH /users/:first_name
For this route, we can handle 415 Unsupported Media Type
, 404 Not Found
, 410 Gone
and 400 Bad Request
. You can get inspired by what we did for POST /users/:first_name
and GET /users/:first_name
. Below, you will find curl
commands to test if you have correctly implemented each status code.
Testing 415
curl -X PATCH -i http://localhost:4567/users/thibault -H "Content-Type: application/fake" -d 'Weirdly Formatted Data'
Testing 400
curl -X PATCH -i http://localhost:4567/users/thibault -H "Content-Type: application/json" -d '{"first_name":"Tibo"'
Testing 404
curl -X PATCH -i http://localhost:4567/users/mark -H "Content-Type: application/json" -d '{"first_name":"Marc"}'
Testing 410
curl -i -X DELETE http://localhost:4567/users/simon
curl -X PATCH -i http://localhost:4567/users/simon -H "Content-Type: application/json" -d '{"first_name":"Super Simon"}'
6.7. Wrap Up
In this chapter, we’ve seen how to implement errors to let our clients understand exactly what went wrong when something didn’t go as planned.
In the next chapter, we will tackle a sensitive subject: versioning!
Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
Abstract
The Hypertext Transfer Protocol (HTTP) is a stateless application-level protocol for distributed, collaborative, hypertext information systems. This document defines the semantics of HTTP/1.1 messages, as expressed by request methods, request header fields, response status codes, and response header fields, along with the payload of messages (metadata and body content) and mechanisms for content negotiation.
Status of This Memo
This is an Internet Standards Track document.
This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in Section 2 of RFC 5741.
Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at http://www.rfc-editor.org/info/rfc7231.
Copyright Notice
Copyright (c) 2014 IETF Trust and the persons identified as the document authors. All rights reserved.
This document is subject to BCP 78 and the IETF Trust’s Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.
This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English.
- 1. Introduction
- 1.1. Conformance and Error Handling
- 1.2. Syntax Notation
- 2. Resources
- 3. Representations
- 3.1. Representation Metadata
- 3.1.1. Processing Representation Data
- 3.1.2. Encoding for Compression or Integrity
- 3.1.3. Audience Language
- 3.1.4. Identification
- 3.2. Representation Data
- 3.3. Payload Semantics
- 3.4. Content Negotiation
- 3.4.1. Proactive Negotiation
- 3.4.2. Reactive Negotiation
- 3.1. Representation Metadata
- 4. Request Methods
- 4.1. Overview
- 4.2. Common Method Properties
- 4.2.1. Safe Methods
- 4.2.2. Idempotent Methods
- 4.2.3. Cacheable Methods
- 4.3. Method Definitions
- 4.3.1. GET
- 4.3.2. HEAD
- 4.3.3. POST
- 4.3.4. PUT
- 4.3.5. DELETE
- 4.3.6. CONNECT
- 4.3.7. OPTIONS
- 4.3.8. TRACE
- 5. Request Header Fields
- 5.1. Controls
- 5.1.1. Expect
- 5.1.2. Max-Forwards
- 5.2. Conditionals
- 5.3. Content Negotiation
- 5.3.1. Quality Values
- 5.3.2. Accept
- 5.3.3. Accept-Charset
- 5.3.4. Accept-Encoding
- 5.3.5. Accept-Language
- 5.4. Authentication Credentials
- 5.5. Request Context
- 5.5.1. From
- 5.5.2. Referer
- 5.5.3. User-Agent
- 5.1. Controls
- 6. Response Status Codes
- 6.1. Overview of Status Codes
- 6.2. Informational 1xx
- 6.2.1. 100 Continue
- 6.2.2. 101 Switching Protocols
- 6.3. Successful 2xx
- 6.3.1. 200 OK
- 6.3.2. 201 Created
- 6.3.3. 202 Accepted
- 6.3.4. 203 Non-Authoritative Information
- 6.3.5. 204 No Content
- 6.3.6. 205 Reset Content
- 6.4. Redirection 3xx
- 6.4.1. 300 Multiple Choices
- 6.4.2. 301 Moved Permanently
- 6.4.3. 302 Found
- 6.4.4. 303 See Other
- 6.4.5. 305 Use Proxy
- 6.4.6. 306 (Unused)
- 6.4.7. 307 Temporary Redirect
- 6.5. Client Error 4xx
- 6.5.1. 400 Bad Request
- 6.5.2. 402 Payment Required
- 6.5.3. 403 Forbidden
- 6.5.4. 404 Not Found
- 6.5.5. 405 Method Not Allowed
- 6.5.6. 406 Not Acceptable
- 6.5.7. 408 Request Timeout
- 6.5.8. 409 Conflict
- 6.5.9. 410 Gone
- 6.5.10. 411 Length Required
- 6.5.11. 413 Payload Too Large
- 6.5.12. 414 URI Too Long
- 6.5.13. 415 Unsupported Media Type
- 6.5.14. 417 Expectation Failed
- 6.5.15. 426 Upgrade Required
- 6.6. Server Error 5xx
- 6.6.1. 500 Internal Server Error
- 6.6.2. 501 Not Implemented
- 6.6.3. 502 Bad Gateway
- 6.6.4. 503 Service Unavailable
- 6.6.5. 504 Gateway Timeout
- 6.6.6. 505 HTTP Version Not Supported
- 7. Response Header Fields
- 7.1. Control Data
- 7.1.1. Origination Date
- 7.1.2. Location
- 7.1.3. Retry-After
- 7.1.4. Vary
- 7.2. Validator Header Fields
- 7.3. Authentication Challenges
- 7.4. Response Context
- 7.4.1. Allow
- 7.4.2. Server
- 7.1. Control Data
- 8. IANA Considerations
- 8.1. Method Registry
- 8.1.1. Procedure
- 8.1.2. Considerations for New Methods
- 8.1.3. Registrations
- 8.2. Status Code Registry
- 8.2.1. Procedure
- 8.2.2. Considerations for New Status Codes
- 8.2.3. Registrations
- 8.3. Header Field Registry
- 8.3.1. Considerations for New Header Fields
- 8.3.2. Registrations
- 8.4. Content Coding Registry
- 8.4.1. Procedure
- 8.4.2. Registrations
- 8.1. Method Registry
- 9. Security Considerations
- 9.1. Attacks Based on File and Path Names
- 9.2. Attacks Based on Command, Code, or Query Injection
- 9.3. Disclosure of Personal Information
- 9.4. Disclosure of Sensitive Information in URIs
- 9.5. Disclosure of Fragment after Redirects
- 9.6. Disclosure of Product Information
- 9.7. Browser Fingerprinting
- 10. Acknowledgments
- 11. References
- 11.1. Normative References
- 11.2. Informative References
- Appendix A. Differences between HTTP and MIME
- A.1. MIME-Version
- A.2. Conversion to Canonical Form
- A.3. Conversion of Date Formats
- A.4. Conversion of Content-Encoding
- A.5. Conversion of Content-Transfer-Encoding
- A.6. MHTML and Line Length Limitations
- Appendix B. Changes from RFC 2616
- Appendix C. Imported ABNF
- Appendix D. Collected ABNF
- Index
- Authors’ Addresses
1. Introduction
Each Hypertext Transfer Protocol (HTTP) message is either a request or a response. A server listens on a connection for a request, parses each message received, interprets the message semantics in relation to the identified request target, and responds to that request with one or more response messages. A client constructs request messages to communicate specific intentions, examines received responses to see if the intentions were carried out, and determines how to interpret the results. This document defines HTTP/1.1 request and response semantics in terms of the architecture defined in [RFC7230].
HTTP provides a uniform interface for interacting with a resource (Section 2), regardless of its type, nature, or implementation, via the manipulation and transfer of representations (Section 3).
HTTP semantics include the intentions defined by each request method (Section 4), extensions to those semantics that might be described in request header fields (Section 5), the meaning of status codes to indicate a machine-readable response (Section 6), and the meaning of other control data and resource metadata that might be given in response header fields (Section 7).
This document also defines representation metadata that describe how a payload is intended to be interpreted by a recipient, the request header fields that might influence content selection, and the various selection algorithms that are collectively referred to as «content negotiation» (Section 3.4).
1.1. Conformance and Error Handling
The key words «MUST», «MUST NOT», «REQUIRED», «SHALL», «SHALL NOT», «SHOULD», «SHOULD NOT», «RECOMMENDED», «MAY», and «OPTIONAL» in this document are to be interpreted as described in [RFC2119].
Conformance criteria and considerations regarding error handling are defined in Section 2.5 of [RFC7230].
1.2. Syntax Notation
This specification uses the Augmented Backus-Naur Form (ABNF) notation of [RFC5234] with a list extension, defined in Section 7 of [RFC7230], that allows for compact definition of comma-separated lists using a ‘#’ operator (similar to how the ‘*’ operator indicates repetition). Appendix C describes rules imported from other documents. Appendix D shows the collected grammar with all list operators expanded to standard ABNF notation.
This specification uses the terms «character», «character encoding scheme», «charset», and «protocol element» as they are defined in [RFC6365].
2. Resources
The target of an HTTP request is called a «resource«. HTTP does not limit the nature of a resource; it merely defines an interface that might be used to interact with resources. Each resource is identified by a Uniform Resource Identifier (URI), as described in Section 2.7 of [RFC7230].
When a client constructs an HTTP/1.1 request message, it sends the target URI in one of various forms, as defined in (Section 5.3 of [RFC7230]). When a request is received, the server reconstructs an effective request URI for the target resource (Section 5.5 of [RFC7230]).
One design goal of HTTP is to separate resource identification from request semantics, which is made possible by vesting the request semantics in the request method (Section 4) and a few request-modifying header fields (Section 5). If there is a conflict between the method semantics and any semantic implied by the URI itself, as described in Section 4.2.1, the method semantics take precedence.
3. Representations
Considering that a resource could be anything, and that the uniform interface provided by HTTP is similar to a window through which one can observe and act upon such a thing only through the communication of messages to some independent actor on the other side, an abstraction is needed to represent («take the place of») the current or desired state of that thing in our communications. That abstraction is called a representation [REST].
For the purposes of HTTP, a «representation» is information that is intended to reflect a past, current, or desired state of a given resource, in a format that can be readily communicated via the protocol, and that consists of a set of representation metadata and a potentially unbounded stream of representation data.
An origin server might be provided with, or be capable of generating, multiple representations that are each intended to reflect the current state of a target resource. In such cases, some algorithm is used by the origin server to select one of those representations as most applicable to a given request, usually based on content negotiation. This «selected representation» is used to provide the data and metadata for evaluating conditional requests [RFC7232] and constructing the payload for 200 (OK) and 304 (Not Modified) responses to GET (Section 4.3.1).
3.1. Representation Metadata
Representation header fields provide metadata about the representation. When a message includes a payload body, the representation header fields describe how to interpret the representation data enclosed in the payload body. In a response to a HEAD request, the representation header fields describe the representation data that would have been enclosed in the payload body if the same request had been a GET.
The following header fields convey representation metadata:
Header Field Name | Defined in… |
---|---|
Content-Type | Section 3.1.1.5 |
Content-Encoding | Section 3.1.2.2 |
Content-Language | Section 3.1.3.2 |
Content-Location | Section 3.1.4.2 |
3.1.1. Processing Representation Data
3.1.1.1. Media Type
HTTP uses Internet media types [RFC2046] in the Content-Type (Section 3.1.1.5) and Accept (Section 5.3.2) header fields in order to provide open and extensible data typing and type negotiation. Media types define both a data format and various processing models: how to process that data in accordance with each context in which it is received.
The type/subtype MAY be followed by parameters in the form of name=value pairs.
The type, subtype, and parameter name tokens are case-insensitive. Parameter values might or might not be case-sensitive, depending on the semantics of the parameter name. The presence or absence of a parameter might be significant to the processing of a media-type, depending on its definition within the media type registry.
A parameter value that matches the token production can be transmitted either as a token or within a quoted-string. The quoted and unquoted values are equivalent. For example, the following examples are all equivalent, but the first is preferred for consistency:
text/html;charset=utf-8 text/html;charset=UTF-8 Text/HTML;Charset="utf-8" text/html; charset="utf-8"
Internet media types ought to be registered with IANA according to the procedures defined in [BCP13].
3.1.1.2. Charset
HTTP uses charset names to indicate or negotiate the character encoding scheme of a textual representation [RFC6365]. A charset is identified by a case-insensitive token.
3.1.1.3. Canonicalization and Text Defaults
Internet media types are registered with a canonical form in order to be interoperable among systems with varying native encoding formats. Representations selected or transferred via HTTP ought to be in canonical form, for many of the same reasons described by the Multipurpose Internet Mail Extensions (MIME) [RFC2045]. However, the performance characteristics of email deployments (i.e., store and forward messages to peers) are significantly different from those common to HTTP and the Web (server-based information services). Furthermore, MIME’s constraints for the sake of compatibility with older mail transfer protocols do not apply to HTTP (see Appendix A).
MIME’s canonical form requires that media subtypes of the «text» type use CRLF as the text line break. HTTP allows the transfer of text media with plain CR or LF alone representing a line break, when such line breaks are consistent for an entire representation. An HTTP sender MAY generate, and a recipient MUST be able to parse, line breaks in text media that consist of CRLF, bare CR, or bare LF. In addition, text media in HTTP is not limited to charsets that use octets 13 and 10 for CR and LF, respectively. This flexibility regarding line breaks applies only to text within a representation that has been assigned a «text» media type; it does not apply to «multipart» types or HTTP elements outside the payload body (e.g., header fields).
If a representation is encoded with a content-coding, the underlying data ought to be in a form defined above prior to being encoded.
3.1.1.4. Multipart Types
MIME provides for a number of «multipart» types — encapsulations of one or more representations within a single message body. All multipart types share a common syntax, as defined in Section 5.1.1 of [RFC2046], and include a boundary parameter as part of the media type value. The message body is itself a protocol element; a sender MUST generate only CRLF to represent line breaks between body parts.
HTTP message framing does not use the multipart boundary as an indicator of message body length, though it might be used by implementations that generate or process the payload. For example, the «multipart/form-data» type is often used for carrying form data in a request, as described in [RFC2388], and the «multipart/byteranges» type is defined by this specification for use in some 206 (Partial Content) responses [RFC7233].
3.1.1.5. Content-Type
The «Content-Type» header field indicates the media type of the associated representation: either the representation enclosed in the message payload or the selected representation, as determined by the message semantics. The indicated media type defines both the data format and how that data is intended to be processed by a recipient, within the scope of the received message semantics, after any content codings indicated by Content-Encoding are decoded.
Media types are defined in Section 3.1.1.1. An example of the field is
Content-Type: text/html; charset=ISO-8859-4
A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender. If a Content-Type header field is not present, the recipient MAY either assume a media type of «application/octet-stream» ([RFC2046], Section 4.5.1) or examine the data to determine its type.
In practice, resource owners do not always properly configure their origin server to provide the correct Content-Type for a given representation, with the result that some clients will examine a payload’s content and override the specified type. Clients that do so risk drawing incorrect conclusions, which might expose additional security risks (e.g., «privilege escalation»). Furthermore, it is impossible to determine the sender’s intent by examining the data format: many data formats match multiple media types that differ only in processing semantics. Implementers are encouraged to provide a means of disabling such «content sniffing» when it is used.
3.1.2. Encoding for Compression or Integrity
3.1.2.1. Content Codings
Content coding values indicate an encoding transformation that has been or can be applied to a representation. Content codings are primarily used to allow a representation to be compressed or otherwise usefully transformed without losing the identity of its underlying media type and without loss of information. Frequently, the representation is stored in coded form, transmitted directly, and only decoded by the final recipient.
All content-coding values are case-insensitive and ought to be registered within the «HTTP Content Coding Registry», as defined in Section 8.4. They are used in the Accept-Encoding (Section 5.3.4) and Content-Encoding (Section 3.1.2.2) header fields.
3.1.2.2. Content-Encoding
The «Content-Encoding» header field indicates what content codings have been applied to the representation, beyond those inherent in the media type, and thus what decoding mechanisms have to be applied in order to obtain data in the media type referenced by the Content-Type header field. Content-Encoding is primarily used to allow a representation’s data to be compressed without losing the identity of its underlying media type.
An example of its use is
If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied. Additional information about the encoding parameters can be provided by other header fields not defined by this specification.
Unlike Transfer-Encoding (Section 3.3.1 of [RFC7230]), the codings listed in Content-Encoding are a characteristic of the representation; the representation is defined in terms of the coded form, and all other metadata about the representation is about the coded form unless otherwise noted in the metadata definition. Typically, the representation is only decoded just prior to rendering or analogous usage.
If the media type includes an inherent encoding, such as a data format that is always compressed, then that encoding would not be restated in Content-Encoding even if it happens to be the same algorithm as one of the content codings. Such a content coding would only be listed if, for some bizarre reason, it is applied a second time to form the representation. Likewise, an origin server might choose to publish the same data as multiple representations that differ only in whether the coding is defined as part of Content-Type or Content-Encoding, since some user agents will behave differently in their handling of each response (e.g., open a «Save as …» dialog instead of automatic decompression and rendering of content).
An origin server MAY respond with a status code of 415 (Unsupported Media Type) if a representation in the request message has a content coding that is not acceptable.
3.1.3. Audience Language
3.1.3.1. Language Tags
A language tag, as defined in [RFC5646], identifies a natural language spoken, written, or otherwise conveyed by human beings for communication of information to other human beings. Computer languages are explicitly excluded.
HTTP uses language tags within the Accept-Language and Content-Language header fields. Accept-Language uses the broader language-range production defined in Section 5.3.5, whereas Content-Language uses the language-tag production defined below.
A language tag is a sequence of one or more case-insensitive subtags, each separated by a hyphen character («-«, %x2D). In most cases, a language tag consists of a primary language subtag that identifies a broad family of related languages (e.g., «en» = English), which is optionally followed by a series of subtags that refine or narrow that language’s range (e.g., «en-CA» = the variety of English as communicated in Canada). Whitespace is not allowed within a language tag. Example tags include:
fr, en-US, es-419, az-Arab, x-pig-latin, man-Nkoo-GN
See [RFC5646] for further information.
3.1.3.2. Content-Language
The «Content-Language» header field describes the natural language(s) of the intended audience for the representation. Note that this might not be equivalent to all the languages used within the representation.
Language tags are defined in Section 3.1.3.1. The primary purpose of Content-Language is to allow a user to identify and differentiate representations according to the users’ own preferred language. Thus, if the content is intended only for a Danish-literate audience, the appropriate field is
If no Content-Language is specified, the default is that the content is intended for all language audiences. This might mean that the sender does not consider it to be specific to any natural language, or that the sender does not know for which language it is intended.
Multiple languages MAY be listed for content that is intended for multiple audiences. For example, a rendition of the «Treaty of Waitangi», presented simultaneously in the original Maori and English versions, would call for
However, just because multiple languages are present within a representation does not mean that it is intended for multiple linguistic audiences. An example would be a beginner’s language primer, such as «A First Lesson in Latin», which is clearly intended to be used by an English-literate audience. In this case, the Content-Language would properly only include «en».
Content-Language MAY be applied to any media type — it is not limited to textual documents.
3.1.4. Identification
3.1.4.1. Identifying a Representation
When a complete or partial representation is transferred in a message payload, it is often desirable for the sender to supply, or the recipient to determine, an identifier for a resource corresponding to that representation.
For a request message:
- If the request has a Content-Location header field, then the sender asserts that the payload is a representation of the resource identified by the Content-Location field-value. However, such an assertion cannot be trusted unless it can be verified by other means (not defined by this specification). The information might still be useful for revision history links.
- Otherwise, the payload is unidentified.
For a response message, the following rules are applied in order until a match is found:
- If the request method is GET or HEAD and the response status code is 200 (OK), 204 (No Content), 206 (Partial Content), or 304 (Not Modified), the payload is a representation of the resource identified by the effective request URI (Section 5.5 of [RFC7230]).
- If the request method is GET or HEAD and the response status code is 203 (Non-Authoritative Information), the payload is a potentially modified or enhanced representation of the target resource as provided by an intermediary.
- If the response has a Content-Location header field and its field-value is a reference to the same URI as the effective request URI, the payload is a representation of the resource identified by the effective request URI.
- If the response has a Content-Location header field and its field-value is a reference to a URI different from the effective request URI, then the sender asserts that the payload is a representation of the resource identified by the Content-Location field-value. However, such an assertion cannot be trusted unless it can be verified by other means (not defined by this specification).
- Otherwise, the payload is unidentified.
3.1.4.2. Content-Location
The «Content-Location» header field references a URI that can be used as an identifier for a specific resource corresponding to the representation in this message’s payload. In other words, if one were to perform a GET request on this URI at the time of this message’s generation, then a 200 (OK) response would contain the same representation that is enclosed as payload in this message.
The Content-Location value is not a replacement for the effective Request URI (Section 5.5 of [RFC7230]). It is representation metadata. It has the same syntax and semantics as the header field of the same name defined for MIME body parts in Section 4 of [RFC2557]. However, its appearance in an HTTP message has some special implications for HTTP recipients.
If Content-Location is included in a 2xx (Successful) response message and its value refers (after conversion to absolute form) to a URI that is the same as the effective request URI, then the recipient MAY consider the payload to be a current representation of that resource at the time indicated by the message origination date. For a GET (Section 4.3.1) or HEAD (Section 4.3.2) request, this is the same as the default semantics when no Content-Location is provided by the server. For a state-changing request like PUT (Section 4.3.4) or POST (Section 4.3.3), it implies that the server’s response contains the new representation of that resource, thereby distinguishing it from representations that might only report about the action (e.g., «It worked!»). This allows authoring applications to update their local copies without the need for a subsequent GET request.
If Content-Location is included in a 2xx (Successful) response message and its field-value refers to a URI that differs from the effective request URI, then the origin server claims that the URI is an identifier for a different resource corresponding to the enclosed representation. Such a claim can only be trusted if both identifiers share the same resource owner, which cannot be programmatically determined via HTTP.
- For a response to a GET or HEAD request, this is an indication that the effective request URI refers to a resource that is subject to content negotiation and the Content-Location field-value is a more specific identifier for the selected representation.
- For a 201 (Created) response to a state-changing method, a Content-Location field-value that is identical to the Location field-value indicates that this payload is a current representation of the newly created resource.
- Otherwise, such a Content-Location indicates that this payload is a representation reporting on the requested action’s status and that the same report is available (for future access with GET) at the given URI. For example, a purchase transaction made via a POST request might include a receipt document as the payload of the 200 (OK) response; the Content-Location field-value provides an identifier for retrieving a copy of that same receipt in the future.
A user agent that sends Content-Location in a request message is stating that its value refers to where the user agent originally obtained the content of the enclosed representation (prior to any modifications made by that user agent). In other words, the user agent is providing a back link to the source of the original representation.
An origin server that receives a Content-Location field in a request message MUST treat the information as transitory request context rather than as metadata to be saved verbatim as part of the representation. An origin server MAY use that context to guide in processing the request or to save it for other uses, such as within source links or versioning metadata. However, an origin server MUST NOT use such context information to alter the request semantics.
For example, if a client makes a PUT request on a negotiated resource and the origin server accepts that PUT (without redirection), then the new state of that resource is expected to be consistent with the one representation supplied in that PUT; the Content-Location cannot be used as a form of reverse content selection identifier to update only one of the negotiated representations. If the user agent had wanted the latter semantics, it would have applied the PUT directly to the Content-Location URI.
3.2. Representation Data
The representation data associated with an HTTP message is either provided as the payload body of the message or referred to by the message semantics and the effective request URI. The representation data is in a format and encoding defined by the representation metadata header fields.
The data type of the representation data is determined via the header fields Content-Type and Content-Encoding. These define a two-layer, ordered encoding model:
representation-data := Content-Encoding( Content-Type( bits ) )
3.3. Payload Semantics
Some HTTP messages transfer a complete or partial representation as the message «payload«. In some cases, a payload might contain only the associated representation’s header fields (e.g., responses to HEAD) or only some part(s) of the representation data (e.g., the 206 (Partial Content) status code).
The purpose of a payload in a request is defined by the method semantics. For example, a representation in the payload of a PUT request (Section 4.3.4) represents the desired state of the target resource if the request is successfully applied, whereas a representation in the payload of a POST request (Section 4.3.3) represents information to be processed by the target resource.
In a response, the payload’s purpose is defined by both the request method and the response status code. For example, the payload of a 200 (OK) response to GET (Section 4.3.1) represents the current state of the target resource, as observed at the time of the message origination date (Section 7.1.1.2), whereas the payload of the same status code in a response to POST might represent either the processing result or the new state of the target resource after applying the processing. Response messages with an error status code usually contain a payload that represents the error condition, such that it describes the error state and what next steps are suggested for resolving it.
Header fields that specifically describe the payload, rather than the associated representation, are referred to as «payload header fields». Payload header fields are defined in other parts of this specification, due to their impact on message parsing.
3.4. Content Negotiation
When responses convey payload information, whether indicating a success or an error, the origin server often has different ways of representing that information; for example, in different formats, languages, or encodings. Likewise, different users or user agents might have differing capabilities, characteristics, or preferences that could influence which representation, among those available, would be best to deliver. For this reason, HTTP provides mechanisms for content negotiation.
This specification defines two patterns of content negotiation that can be made visible within the protocol: «proactive», where the server selects the representation based upon the user agent’s stated preferences, and «reactive» negotiation, where the server provides a list of representations for the user agent to choose from. Other patterns of content negotiation include «conditional content», where the representation consists of multiple parts that are selectively rendered based on user agent parameters, «active content», where the representation contains a script that makes additional (more specific) requests based on the user agent characteristics, and «Transparent Content Negotiation» ([RFC2295]), where content selection is performed by an intermediary. These patterns are not mutually exclusive, and each has trade-offs in applicability and practicality.
Note that, in all cases, HTTP is not aware of the resource semantics. The consistency with which an origin server responds to requests, over time and over the varying dimensions of content negotiation, and thus the «sameness» of a resource’s observed representations over time, is determined entirely by whatever entity or algorithm selects or generates those responses. HTTP pays no attention to the man behind the curtain.
3.4.1. Proactive Negotiation
When content negotiation preferences are sent by the user agent in a request to encourage an algorithm located at the server to select the preferred representation, it is called proactive negotiation (a.k.a., server-driven negotiation). Selection is based on the available representations for a response (the dimensions over which it might vary, such as language, content-coding, etc.) compared to various information supplied in the request, including both the explicit negotiation fields of Section 5.3 and implicit characteristics, such as the client’s network address or parts of the User-Agent field.
Proactive negotiation is advantageous when the algorithm for selecting from among the available representations is difficult to describe to a user agent, or when the server desires to send its «best guess» to the user agent along with the first response (hoping to avoid the round trip delay of a subsequent request if the «best guess» is good enough for the user). In order to improve the server’s guess, a user agent MAY send request header fields that describe its preferences.
Proactive negotiation has serious disadvantages:
- It is impossible for the server to accurately determine what might be «best» for any given user, since that would require complete knowledge of both the capabilities of the user agent and the intended use for the response (e.g., does the user want to view it on screen or print it on paper?);
- Having the user agent describe its capabilities in every request can be both very inefficient (given that only a small percentage of responses have multiple representations) and a potential risk to the user’s privacy;
- It complicates the implementation of an origin server and the algorithms for generating responses to a request; and,
- It limits the reusability of responses for shared caching.
A user agent cannot rely on proactive negotiation preferences being consistently honored, since the origin server might not implement proactive negotiation for the requested resource or might decide that sending a response that doesn’t conform to the user agent’s preferences is better than sending a 406 (Not Acceptable) response.
A Vary header field (Section 7.1.4) is often sent in a response subject to proactive negotiation to indicate what parts of the request information were used in the selection algorithm.
3.4.2. Reactive Negotiation
With reactive negotiation (a.k.a., agent-driven negotiation), selection of the best response representation (regardless of the status code) is performed by the user agent after receiving an initial response from the origin server that contains a list of resources for alternative representations. If the user agent is not satisfied by the initial response representation, it can perform a GET request on one or more of the alternative resources, selected based on metadata included in the list, to obtain a different form of representation for that response. Selection of alternatives might be performed automatically by the user agent or manually by the user selecting from a generated (possibly hypertext) menu.
Note that the above refers to representations of the response, in general, not representations of the resource. The alternative representations are only considered representations of the target resource if the response in which those alternatives are provided has the semantics of being a representation of the target resource (e.g., a 200 (OK) response to a GET request) or has the semantics of providing links to alternative representations for the target resource (e.g., a 300 (Multiple Choices) response to a GET request).
A server might choose not to send an initial representation, other than the list of alternatives, and thereby indicate that reactive negotiation by the user agent is preferred. For example, the alternatives listed in responses with the 300 (Multiple Choices) and 406 (Not Acceptable) status codes include information about the available representations so that the user or user agent can react by making a selection.
Reactive negotiation is advantageous when the response would vary over commonly used dimensions (such as type, language, or encoding), when the origin server is unable to determine a user agent’s capabilities from examining the request, and generally when public caches are used to distribute server load and reduce network usage.
Reactive negotiation suffers from the disadvantages of transmitting a list of alternatives to the user agent, which degrades user-perceived latency if transmitted in the header section, and needing a second request to obtain an alternate representation. Furthermore, this specification does not define a mechanism for supporting automatic selection, though it does not prevent such a mechanism from being developed as an extension.
4. Request Methods
4.1. Overview
The request method token is the primary source of request semantics; it indicates the purpose for which the client has made this request and what is expected by the client as a successful result.
The request method’s semantics might be further specialized by the semantics of some header fields when present in a request (Section 5) if those additional semantics do not conflict with the method. For example, a client can send conditional request header fields (Section 5.2) to make the requested action conditional on the current state of the target resource ([RFC7232]).
HTTP was originally designed to be usable as an interface to distributed object systems. The request method was envisioned as applying semantics to a target resource in much the same way as invoking a defined method on an identified object would apply semantics. The method token is case-sensitive because it might be used as a gateway to object-based systems with case-sensitive method names.
Unlike distributed objects, the standardized request methods in HTTP are not resource-specific, since uniform interfaces provide for better visibility and reuse in network-based systems [REST]. Once defined, a standardized method ought to have the same semantics when applied to any resource, though each resource determines for itself whether those semantics are implemented or allowed.
This specification defines a number of standardized methods that are commonly used in HTTP, as outlined by the following table. By convention, standardized methods are defined in all-uppercase US-ASCII letters.
Method | Description | Sec. |
---|---|---|
GET | Transfer a current representation of the target resource. | 4.3.1 |
HEAD | Same as GET, but only transfer the status line and header section. | 4.3.2 |
POST | Perform resource-specific processing on the request payload. | 4.3.3 |
PUT | Replace all current representations of the target resource with the request payload. | 4.3.4 |
DELETE | Remove all current representations of the target resource. | 4.3.5 |
CONNECT | Establish a tunnel to the server identified by the target resource. | 4.3.6 |
OPTIONS | Describe the communication options for the target resource. | 4.3.7 |
TRACE | Perform a message loop-back test along the path to the target resource. | 4.3.8 |
All general-purpose servers MUST support the methods GET and HEAD. All other methods are OPTIONAL.
Additional methods, outside the scope of this specification, have been standardized for use in HTTP. All such methods ought to be registered within the «Hypertext Transfer Protocol (HTTP) Method Registry» maintained by IANA, as defined in Section 8.1.
The set of methods allowed by a target resource can be listed in an Allow header field (Section 7.4.1). However, the set of allowed methods can change dynamically. When a request method is received that is unrecognized or not implemented by an origin server, the origin server SHOULD respond with the 501 (Not Implemented) status code. When a request method is received that is known by an origin server but not allowed for the target resource, the origin server SHOULD respond with the 405 (Method Not Allowed) status code.
4.2. Common Method Properties
4.2.1. Safe Methods
Request methods are considered «safe» if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server.
This definition of safe methods does not prevent an implementation from including behavior that is potentially harmful, that is not entirely read-only, or that causes side effects while invoking a safe method. What is important, however, is that the client did not request that additional behavior and cannot be held accountable for it. For example, most servers append request information to access log files at the completion of every response, regardless of the method, and that is considered safe even though the log storage might become full and crash the server. Likewise, a safe request initiated by selecting an advertisement on the Web will often have the side effect of charging an advertising account.
Of the request methods defined by this specification, the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.
The purpose of distinguishing between safe and unsafe methods is to allow automated retrieval processes (spiders) and cache performance optimization (pre-fetching) to work without fear of causing harm. In addition, it allows a user agent to apply appropriate constraints on the automated use of unsafe methods when processing potentially untrusted content.
A user agent SHOULD distinguish between safe and unsafe methods when presenting potential actions to a user, such that the user can be made aware of an unsafe action before it is requested.
When a resource is constructed such that parameters within the effective request URI have the effect of selecting an action, it is the resource owner’s responsibility to ensure that the action is consistent with the request method semantics. For example, it is common for Web-based content editing software to use actions within query parameters, such as «page?do=delete». If the purpose of such a resource is to perform an unsafe action, then the resource owner MUST disable or disallow that action when it is accessed using a safe request method. Failure to do so will result in unfortunate side effects when automated processes perform a GET on every URI reference for the sake of link maintenance, pre-fetching, building a search index, etc.
4.2.2. Idempotent Methods
A request method is considered «idempotent» if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent.
Like the definition of safe, the idempotent property only applies to what has been requested by the user; a server is free to log each request separately, retain a revision control history, or implement other non-idempotent side effects for each idempotent request.
Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server’s response. For example, if a client sends a PUT request and the underlying connection is closed before any response is received, then the client can establish a new connection and retry the idempotent request. It knows that repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ.
4.2.3. Cacheable Methods
Request methods can be defined as «cacheable» to indicate that responses to them are allowed to be stored for future reuse; for specific requirements see [RFC7234]. In general, safe methods that do not depend on a current or authoritative response are defined as cacheable; this specification defines GET, HEAD, and POST as cacheable, although the overwhelming majority of cache implementations only support GET and HEAD.
4.3. Method Definitions
4.3.1. GET
The GET method requests transfer of a current selected representation for the target resource. GET is the primary mechanism of information retrieval and the focus of almost all performance optimizations. Hence, when people speak of retrieving some identifiable information via HTTP, they are generally referring to making a GET request.
It is tempting to think of resource identifiers as remote file system pathnames and of representations as being a copy of the contents of such files. In fact, that is how many resources are implemented (see Section 9.1 for related security considerations). However, there are no such limitations in practice. The HTTP interface for a resource is just as likely to be implemented as a tree of content objects, a programmatic view on various database records, or a gateway to other information systems. Even when the URI mapping mechanism is tied to a file system, an origin server might be configured to execute the files with the request as input and send the output as the representation rather than transfer the files directly. Regardless, only the origin server needs to know how each of its resource identifiers corresponds to an implementation and how each implementation manages to select and send a current representation of the target resource in a response to GET.
A client can alter the semantics of GET to be a «range request», requesting transfer of only some part(s) of the selected representation, by sending a Range header field in the request ([RFC7233]).
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
The response to a GET request is cacheable; a cache MAY use it to satisfy subsequent GET and HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [RFC7234]).
4.3.2. HEAD
The HEAD method is identical to GET except that the server MUST NOT send a message body in the response (i.e., the response terminates at the end of the header section). The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request had been a GET, except that the payload header fields (Section 3.3) MAY be omitted. This method can be used for obtaining metadata about the selected representation without transferring the representation data and is often used for testing hypertext links for validity, accessibility, and recent modification.
A payload within a HEAD request message has no defined semantics; sending a payload body on a HEAD request might cause some existing implementations to reject the request.
The response to a HEAD request is cacheable; a cache MAY use it to satisfy subsequent HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [RFC7234]). A HEAD response might also have an effect on previously cached responses to GET; see Section 4.3.5 of [RFC7234].
4.3.3. POST
The POST method requests that the target resource process the representation enclosed in the request according to the resource’s own specific semantics. For example, POST is used for the following functions (among others):
- Providing a block of data, such as the fields entered into an HTML form, to a data-handling process;
- Posting a message to a bulletin board, newsgroup, mailing list, blog, or similar group of articles;
- Creating a new resource that has yet to be identified by the origin server; and
- Appending data to a resource’s existing representation(s).
An origin server indicates response semantics by choosing an appropriate status code depending on the result of processing the POST request; almost all of the status codes defined by this specification might be received in a response to POST (the exceptions being 206 (Partial Content), 304 (Not Modified), and 416 (Range Not Satisfiable)).
If one or more resources has been created on the origin server as a result of successfully processing a POST request, the origin server SHOULD send a 201 (Created) response containing a Location header field that provides an identifier for the primary resource created (Section 7.1.2) and a representation that describes the status of the request while referring to the new resource(s).
Responses to POST requests are only cacheable when they include explicit freshness information (see Section 4.2.1 of [RFC7234]). However, POST caching is not widely implemented. For cases where an origin server wishes the client to be able to cache the result of a POST in a way that can be reused by a later GET, the origin server MAY send a 200 (OK) response containing the result and a Content-Location header field that has the same value as the POST’s effective request URI (Section 3.1.4.2).
If the result of processing a POST would be equivalent to a representation of an existing resource, an origin server MAY redirect the user agent to that resource by sending a 303 (See Other) response with the existing resource’s identifier in the Location field. This has the benefits of providing the user agent a resource identifier and transferring the representation via a method more amenable to shared caching, though at the cost of an extra request if the user agent does not already have the representation cached.
4.3.4. PUT
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response. However, there is no guarantee that such a state change will be observable, since the target resource might be acted upon by other user agents in parallel, or might be subject to dynamic processing by the origin server, before any subsequent GET is received. A successful response only implies that the user agent’s intent was achieved at the time of its processing by the origin server.
If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response. If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the request.
An origin server SHOULD ignore unrecognized header fields received in a PUT request (i.e., do not save them as part of the resource state).
An origin server SHOULD verify that the PUT representation is consistent with any constraints the server has for the target resource that cannot or will not be changed by the PUT. This is particularly important when the origin server uses internal configuration information related to the URI in order to set the values for representation metadata on GET responses. When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable. The 409 (Conflict) or 415 (Unsupported Media Type) status codes are suggested, with the latter being specific to constraints on Content-Type values.
For example, if the target resource is configured to always have a Content-Type of «text/html» and the representation being PUT has a Content-Type of «image/jpeg», the origin server ought to do one of:
- reconfigure the target resource to reflect the new media type;
- transform the PUT representation to a format consistent with that of the resource before saving it as the new resource state; or,
- reject the request with a 415 (Unsupported Media Type) response indicating that the target resource is limited to «text/html», perhaps including a link to a different resource that would be a suitable target for the new representation.
HTTP does not define exactly how a PUT method affects the state of an origin server beyond what can be expressed by the intent of the user agent request and the semantics of the origin server response. It does not define what a resource might be, in any sense of that word, beyond the interface provided via HTTP. It does not define how resource state is «stored», nor how such storage might change as a result of a change in resource state, nor how the origin server translates resource state into representations. Generally speaking, all implementation details behind the resource interface are intentionally hidden by the server.
An origin server MUST NOT send a validator header field (Section 7.2), such as an ETag or Last-Modified field, in a successful response to PUT unless the request’s representation data was saved without any transformation applied to the body (i.e., the resource’s new representation data is identical to the representation data received in the PUT request) and the validator field value reflects the new representation. This requirement allows a user agent to know when the representation body it has in memory remains current as a result of the PUT, thus not in need of being retrieved again from the origin server, and that the new validator(s) received in the response can be used for future conditional requests in order to prevent accidental overwrites (Section 5.2).
The fundamental difference between the POST and PUT methods is highlighted by the different intent for the enclosed representation. The target resource in a POST request is intended to handle the enclosed representation according to the resource’s own semantics, whereas the enclosed representation in a PUT request is defined as replacing the state of the target resource. Hence, the intent of PUT is idempotent and visible to intermediaries, even though the exact effect is only known by the origin server.
Proper interpretation of a PUT request presumes that the user agent knows which target resource is desired. A service that selects a proper URI on behalf of the client, after receiving a state-changing request, SHOULD be implemented using the POST method rather than PUT. If the origin server will not make the requested PUT state change to the target resource and instead wishes to have it applied to a different resource, such as when the resource has been moved to a different URI, then the origin server MUST send an appropriate 3xx (Redirection) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
A PUT request applied to the target resource can have side effects on other resources. For example, an article might have a URI for identifying «the current version» (a resource) that is separate from the URIs identifying each particular version (different resources that at one point shared the same state as the current version resource). A successful PUT request on «the current version» URI might therefore create a new version resource in addition to changing the state of the target resource, and might also cause links to be added between the related resources.
An origin server that allows PUT on a given target resource MUST send a 400 (Bad Request) response to a PUT request that contains a Content-Range header field (Section 4.2 of [RFC7233]), since the payload is likely to be partial content that has been mistakenly PUT as a full representation. Partial content updates are possible by targeting a separately identified resource with state that overlaps a portion of the larger resource, or by using a different method that has been specifically defined for partial updates (for example, the PATCH method defined in [RFC5789]).
Responses to the PUT method are not cacheable. If a successful PUT request passes through a cache that has one or more stored responses for the effective request URI, those stored responses will be invalidated (see Section 4.4 of [RFC7234]).
4.3.5. DELETE
The DELETE method requests that the origin server remove the association between the target resource and its current functionality. In effect, this method is similar to the rm command in UNIX: it expresses a deletion operation on the URI mapping of the origin server rather than an expectation that the previously associated information be deleted.
If the target resource has one or more current representations, they might or might not be destroyed by the origin server, and the associated storage might or might not be reclaimed, depending entirely on the nature of the resource and its implementation by the origin server (which are beyond the scope of this specification). Likewise, other implementation aspects of a resource might need to be deactivated or archived as a result of a DELETE, such as database or gateway connections. In general, it is assumed that the origin server will only allow DELETE on resources for which it has a prescribed mechanism for accomplishing the deletion.
Relatively few resources allow the DELETE method — its primary use is for remote authoring environments, where the user has some direction regarding its effect. For example, a resource that was previously created using a PUT request, or identified via the Location header field after a 201 (Created) response to a POST request, might allow a corresponding DELETE request to undo those actions. Similarly, custom user agent implementations that implement an authoring function, such as revision control clients using HTTP for remote operations, might use DELETE based on an assumption that the server’s URI space has been crafted to correspond to a version repository.
If a DELETE method is successfully applied, the origin server SHOULD send a 202 (Accepted) status code if the action will likely succeed but has not yet been enacted, a 204 (No Content) status code if the action has been enacted and no further information is to be supplied, or a 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
Responses to the DELETE method are not cacheable. If a DELETE request passes through a cache that has one or more stored responses for the effective request URI, those stored responses will be invalidated (see Section 4.4 of [RFC7234]).
4.3.6. CONNECT
The CONNECT method requests that the recipient establish a tunnel to the destination origin server identified by the request-target and, if successful, thereafter restrict its behavior to blind forwarding of packets, in both directions, until the tunnel is closed. Tunnels are commonly used to create an end-to-end virtual connection, through one or more proxies, which can then be secured using TLS (Transport Layer Security, [RFC5246]).
CONNECT is intended only for use in requests to a proxy. An origin server that receives a CONNECT request for itself MAY respond with a 2xx (Successful) status code to indicate that a connection is established. However, most origin servers do not implement CONNECT.
A client sending a CONNECT request MUST send the authority form of request-target (Section 5.3 of [RFC7230]); i.e., the request-target consists of only the host name and port number of the tunnel destination, separated by a colon. For example,
CONNECT server.example.com:80 HTTP/1.1 Host: server.example.com:80
The recipient proxy can establish a tunnel either by directly connecting to the request-target or, if configured to use another proxy, by forwarding the CONNECT request to the next inbound proxy. Any 2xx (Successful) response indicates that the sender (and all inbound proxies) will switch to tunnel mode immediately after the blank line that concludes the successful response’s header section; data received after that blank line is from the server identified by the request-target. Any response other than a successful response indicates that the tunnel has not yet been formed and that the connection remains governed by HTTP.
A tunnel is closed when a tunnel intermediary detects that either side has closed its connection: the intermediary MUST attempt to send any outstanding data that came from the closed side to the other side, close both connections, and then discard any remaining data left undelivered.
Proxy authentication might be used to establish the authority to create a tunnel. For example,
CONNECT server.example.com:80 HTTP/1.1 Host: server.example.com:80 Proxy-Authorization: basic aGVsbG86d29ybGQ=
There are significant risks in establishing a tunnel to arbitrary servers, particularly when the destination is a well-known or reserved TCP port that is not intended for Web traffic. For example, a CONNECT to a request-target of «example.com:25» would suggest that the proxy connect to the reserved port for SMTP traffic; if allowed, that could trick the proxy into relaying spam email. Proxies that support CONNECT SHOULD restrict its use to a limited set of known ports or a configurable whitelist of safe request targets.
A server MUST NOT send any Transfer-Encoding or Content-Length header fields in a 2xx (Successful) response to CONNECT. A client MUST ignore any Content-Length or Transfer-Encoding header fields received in a successful response to CONNECT.
A payload within a CONNECT request message has no defined semantics; sending a payload body on a CONNECT request might cause some existing implementations to reject the request.
Responses to the CONNECT method are not cacheable.
4.3.7. OPTIONS
The OPTIONS method requests information about the communication options available for the target resource, at either the origin server or an intervening intermediary. This method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action.
An OPTIONS request with an asterisk («*») as the request-target (Section 5.3 of [RFC7230]) applies to the server in general rather than to a specific resource. Since a server’s communication options typically depend on the resource, the «*» request is only useful as a «ping» or «no-op» type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 conformance (or lack thereof).
If the request-target is not an asterisk, the OPTIONS request applies to the options that are available when communicating with the target resource.
A server generating a successful response to OPTIONS SHOULD send any header fields that might indicate optional features implemented by the server and applicable to the target resource (e.g., Allow), including potential extensions not defined by this specification. The response payload, if any, might also describe the communication options in a machine or human-readable representation. A standard format for such a representation is not defined by this specification, but might be defined by future extensions to HTTP. A server MUST generate a Content-Length field with a value of «0» if no payload body is to be sent in the response.
A client MAY send a Max-Forwards header field in an OPTIONS request to target a specific recipient in the request chain (see Section 5.1.2). A proxy MUST NOT generate a Max-Forwards header field while forwarding a request unless that request was received with a Max-Forwards field.
A client that generates an OPTIONS request containing a payload body MUST send a valid Content-Type header field describing the representation media type. Although this specification does not define any use for such a payload, future extensions to HTTP might use the OPTIONS body to make more detailed queries about the target resource.
Responses to the OPTIONS method are not cacheable.
4.3.8. TRACE
The TRACE method requests a remote, application-level loop-back of the request message. The final recipient of the request SHOULD reflect the message received, excluding some fields described below, back to the client as the message body of a 200 (OK) response with a Content-Type of «message/http» (Section 8.3.1 of [RFC7230]). The final recipient is either the origin server or the first server to receive a Max-Forwards value of zero (0) in the request (Section 5.1.2).
A client MUST NOT generate header fields in a TRACE request containing sensitive data that might be disclosed by the response. For example, it would be foolish for a user agent to send stored user credentials [RFC7235] or cookies [RFC6265] in a TRACE request. The final recipient of the request SHOULD exclude any request header fields that are likely to contain sensitive data when that recipient generates the response body.
TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information. The value of the Via header field (Section 5.7.1 of [RFC7230]) is of particular interest, since it acts as a trace of the request chain. Use of the Max-Forwards header field allows the client to limit the length of the request chain, which is useful for testing a chain of proxies forwarding messages in an infinite loop.
A client MUST NOT send a message body in a TRACE request.
Responses to the TRACE method are not cacheable.
6. Response Status Codes
The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request.
HTTP status codes are extensible. HTTP clients are not required to understand the meaning of all registered status codes, though such understanding is obviously desirable. However, a client MUST understand the class of any status code, as indicated by the first digit, and treat an unrecognized status code as being equivalent to the x00 status code of that class, with the exception that a recipient MUST NOT cache a response with an unrecognized status code.
For example, if an unrecognized status code of 471 is received by a client, the client can assume that there was something wrong with its request and treat the response as if it had received a 400 (Bad Request) status code. The response message will usually contain a representation that explains the status.
The first digit of the status-code defines the class of response. The last two digits do not have any categorization role. There are five values for the first digit:
- 1xx (Informational): The request was received, continuing process
- 2xx (Successful): The request was successfully received, understood, and accepted
- 3xx (Redirection): Further action needs to be taken in order to complete the request
- 4xx (Client Error): The request contains bad syntax or cannot be fulfilled
- 5xx (Server Error): The server failed to fulfill an apparently valid request
6.1. Overview of Status Codes
The status codes listed below are defined in this specification, Section 4 of [RFC7232], Section 4 of [RFC7233], and Section 3 of [RFC7235]. The reason phrases listed here are only recommendations — they can be replaced by local equivalents without affecting the protocol.
Responses with status codes that are defined as cacheable by default (e.g., 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501 in this specification) can be reused by a cache with heuristic expiration unless otherwise indicated by the method definition or explicit cache controls [RFC7234]; all other status codes are not cacheable by default.
Code | Reason-Phrase | Defined in… |
---|---|---|
100 | Continue | Section 6.2.1 |
101 | Switching Protocols | Section 6.2.2 |
200 | OK | Section 6.3.1 |
201 | Created | Section 6.3.2 |
202 | Accepted | Section 6.3.3 |
203 | Non-Authoritative Information | Section 6.3.4 |
204 | No Content | Section 6.3.5 |
205 | Reset Content | Section 6.3.6 |
206 | Partial Content | Section 4.1 of [RFC7233] |
300 | Multiple Choices | Section 6.4.1 |
301 | Moved Permanently | Section 6.4.2 |
302 | Found | Section 6.4.3 |
303 | See Other | Section 6.4.4 |
304 | Not Modified | Section 4.1 of [RFC7232] |
305 | Use Proxy | Section 6.4.5 |
307 | Temporary Redirect | Section 6.4.7 |
400 | Bad Request | Section 6.5.1 |
401 | Unauthorized | Section 3.1 of [RFC7235] |
402 | Payment Required | Section 6.5.2 |
403 | Forbidden | Section 6.5.3 |
404 | Not Found | Section 6.5.4 |
405 | Method Not Allowed | Section 6.5.5 |
406 | Not Acceptable | Section 6.5.6 |
407 | Proxy Authentication Required | Section 3.2 of [RFC7235] |
408 | Request Timeout | Section 6.5.7 |
409 | Conflict | Section 6.5.8 |
410 | Gone | Section 6.5.9 |
411 | Length Required | Section 6.5.10 |
412 | Precondition Failed | Section 4.2 of [RFC7232] |
413 | Payload Too Large | Section 6.5.11 |
414 | URI Too Long | Section 6.5.12 |
415 | Unsupported Media Type | Section 6.5.13 |
416 | Range Not Satisfiable | Section 4.4 of [RFC7233] |
417 | Expectation Failed | Section 6.5.14 |
426 | Upgrade Required | Section 6.5.15 |
500 | Internal Server Error | Section 6.6.1 |
501 | Not Implemented | Section 6.6.2 |
502 | Bad Gateway | Section 6.6.3 |
503 | Service Unavailable | Section 6.6.4 |
504 | Gateway Timeout | Section 6.6.5 |
505 | HTTP Version Not Supported | Section 6.6.6 |
Note that this list is not exhaustive — it does not include extension status codes defined in other specifications. The complete list of status codes is maintained by IANA. See Section 8.2 for details.
6.2. Informational 1xx
The 1xx (Informational) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response. 1xx responses are terminated by the first empty line after the status-line (the empty line signaling the end of the header section). Since HTTP/1.0 did not define any 1xx status codes, a server MUST NOT send a 1xx response to an HTTP/1.0 client.
A client MUST be able to parse one or more 1xx responses received prior to a final response, even if the client does not expect one. A user agent MAY ignore unexpected 1xx responses.
A proxy MUST forward 1xx responses unless the proxy itself requested the generation of the 1xx response. For example, if a proxy adds an «Expect: 100-continue» field when it forwards a request, then it need not forward the corresponding 100 (Continue) response(s).
6.2.1. 100 Continue
The 100 (Continue) status code indicates that the initial part of a request has been received and has not yet been rejected by the server. The server intends to send a final response after the request has been fully received and acted upon.
When the request contains an Expect header field that includes a 100-continue expectation, the 100 response indicates that the server wishes to receive the request payload body, as described in Section 5.1.1. The client ought to continue sending the request and discard the 100 response.
If the request did not contain an Expect header field containing the 100-continue expectation, the client can simply discard this interim response.
6.2.2. 101 Switching Protocols
The 101 (Switching Protocols) status code indicates that the server understands and is willing to comply with the client’s request, via the Upgrade header field (Section 6.7 of [RFC7230]), for a change in the application protocol being used on this connection. The server MUST generate an Upgrade header field in the response that indicates which protocol(s) will be switched to immediately after the empty line that terminates the 101 response.
It is assumed that the server will only agree to switch protocols when it is advantageous to do so. For example, switching to a newer version of HTTP might be advantageous over older versions, and switching to a real-time, synchronous protocol might be advantageous when delivering resources that use such features.
6.3. Successful 2xx
The 2xx (Successful) class of status code indicates that the client’s request was successfully received, understood, and accepted.
6.3.1. 200 OK
The 200 (OK) status code indicates that the request has succeeded. The payload sent in a 200 response depends on the request method. For the methods defined by this specification, the intended meaning of the payload can be summarized as:
- GET
- a representation of the target resource;
- HEAD
- the same representation as GET, but without the representation data;
- POST
- a representation of the status of, or results obtained from, the action;
- PUT, DELETE
- a representation of the status of the action;
- OPTIONS
- a representation of the communications options;
- TRACE
- a representation of the request message as received by the end server.
Aside from responses to CONNECT, a 200 response always has a payload, though an origin server MAY generate a payload body of zero length. If no payload is desired, an origin server ought to send 204 (No Content) instead. For CONNECT, no payload is allowed because the successful result is a tunnel, which begins immediately after the 200 response header section.
A 200 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.3.2. 201 Created
The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.
The 201 response payload typically describes and links to the resource(s) created. See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.
6.3.3. 202 Accepted
The 202 (Accepted) status code indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility in HTTP for re-sending a status code from an asynchronous operation.
The 202 response is intentionally noncommittal. 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 representation sent with this response ought to describe the request’s current status and point to (or embed) a status monitor that can provide the user with an estimate of when the request will be fulfilled.
6.3.4. 203 Non-Authoritative Information
The 203 (Non-Authoritative Information) status code indicates that the request was successful but the enclosed payload has been modified from that of the origin server’s 200 (OK) response by a transforming proxy (Section 5.7.2 of [RFC7230]). This status code allows the proxy to notify recipients when a transformation has been applied, since that knowledge might impact later decisions regarding the content. For example, future cache validation requests for the content might only be applicable along the same request path (through the same proxies).
The 203 response is similar to the Warning code of 214 Transformation Applied (Section 5.5 of [RFC7234]), which has the advantage of being applicable to responses with any status code.
A 203 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.3.5. 204 No Content
The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. Metadata in the response header fields refer to the target resource and its selected representation after the requested action was applied.
For example, if a 204 status code is received in response to a PUT request and the response contains an ETag header field, then the PUT was successful and the ETag field-value contains the entity-tag for the new representation of that target resource.
The 204 response allows a server to indicate that the action has been successfully applied to the target resource, while implying that the user agent does not need to traverse away from its current «document view» (if any). The server assumes that the user agent will provide some indication of the success to its user, in accord with its own interface, and apply any new or updated metadata in the response to its active representation.
For example, a 204 status code is commonly used with document editing interfaces corresponding to a «save» action, such that the document being saved remains available to the user for editing. It is also frequently used with interfaces that expect automated data transfers to be prevalent, such as within distributed version control systems.
A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.
A 204 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.3.6. 205 Reset Content
The 205 (Reset Content) status code indicates that the server has fulfilled the request and desires that the user agent reset the «document view», which caused the request to be sent, to its original state as received from the origin server.
This response is intended to support a common data entry use case where the user receives content that supports data entry (a form, notepad, canvas, etc.), enters or manipulates data in that space, causes the entered data to be submitted in a request, and then the data entry mechanism is reset for the next entry so that the user can easily initiate another input action.
Since the 205 status code implies that no additional content will be provided, a server MUST NOT generate a payload in a 205 response. In other words, a server MUST do one of the following for a 205 response: a) indicate a zero-length body for the response by including a Content-Length header field with a value of 0; b) indicate a zero-length payload for the response by including a Transfer-Encoding header field with a value of chunked and a message body consisting of a single chunk of zero-length; or, c) close the connection immediately after sending the blank line terminating the header section.
6.4. Redirection 3xx
The 3xx (Redirection) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. If a Location header field (Section 7.1.2) is provided, the user agent MAY automatically redirect its request to the URI referenced by the Location field value, even if the specific status code is not understood. Automatic redirection needs to done with care for methods not known to be safe, as defined in Section 4.2.1, since the user might not wish to redirect an unsafe request.
There are several types of redirects:
-
Redirects that indicate the resource might be available at a different URI, as provided by the Location field, as in the status codes 301 (Moved Permanently), 302 (Found), and 307 (Temporary Redirect).
-
Redirection that offers a choice of matching resources, each capable of representing the original request target, as in the 300 (Multiple Choices) status code.
-
Redirection to a different resource, identified by the Location field, that can represent an indirect response to the request, as in the 303 (See Other) status code.
-
Redirection to a previously cached result, as in the 304 (Not Modified) status code.
A client SHOULD detect and intervene in cyclical redirections (i.e., «infinite» redirection loops).
6.4.1. 300 Multiple Choices
The 300 (Multiple Choices) status code indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers. In other words, the server desires that the user agent engage in reactive negotiation to select the most appropriate representation(s) for its needs (Section 3.4).
If the server has a preferred choice, the server SHOULD generate a Location header field containing a preferred choice’s URI reference. The user agent MAY use the Location field value for automatic redirection.
For request methods other than HEAD, the server SHOULD generate a payload in the 300 response containing a list of representation metadata and URI reference(s) from which the user or user agent can choose the one most preferred. The user agent MAY make a selection from that list automatically if it understands the provided media type. A specific format for automatic selection is not defined by this specification because HTTP tries to remain orthogonal to the definition of its payloads. In practice, the representation is provided in some easily parsed format believed to be acceptable to the user agent, as determined by shared design or content negotiation, or in some commonly accepted hypertext format.
A 300 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.4.2. 301 Moved Permanently
The 301 (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. Clients with link-editing capabilities ought to automatically re-link references to the effective request URI to one or more of the new references sent by the server, where possible.
The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI. The user agent MAY use the Location field value for automatic redirection. The server’s response payload usually contains a short hypertext note with a hyperlink to the new URI(s).
A 301 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.4.3. 302 Found
The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.
The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server’s response payload usually contains a short hypertext note with a hyperlink to the different URI(s).
6.4.4. 303 See Other
The 303 (See Other) status code indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, which is intended to provide an indirect response to the original request. A user agent can perform a retrieval request targeting that URI (a GET or HEAD request if using HTTP), which might also be redirected, and present the eventual result as an answer to the original request. Note that the new URI in the Location header field is not considered equivalent to the effective request URI.
This status code is applicable to any HTTP method. It is primarily used to allow the output of a POST action to redirect the user agent to a selected resource, since doing so provides the information corresponding to the POST response in a form that can be separately identified, bookmarked, and cached, independent of the original request.
A 303 response to a GET request indicates that the origin server does not have a representation of the target resource that can be transferred by the server over HTTP. However, the Location field value refers to a resource that is descriptive of the target resource, such that making a retrieval request on that other resource might result in a representation that is useful to recipients without implying that it represents the original target resource. Note that answers to the questions of what can be represented, what representations are adequate, and what might be a useful description are outside the scope of HTTP.
Except for responses to a HEAD request, the representation of a 303 response ought to contain a short hypertext note with a hyperlink to the same URI reference provided in the Location header field.
6.4.5. 305 Use Proxy
The 305 (Use Proxy) status code was defined in a previous version of this specification and is now deprecated (Appendix B).
6.4.6. 306 (Unused)
The 306 status code was defined in a previous version of this specification, is no longer used, and the code is reserved.
6.4.7. 307 Temporary Redirect
The 307 (Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. Since the redirection can change over time, the client ought to continue using the original effective request URI for future requests.
The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server’s response payload usually contains a short hypertext note with a hyperlink to the different URI(s).
6.5. Client Error 4xx
The 4xx (Client Error) class of status code indicates that the client seems to have erred. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included representation to the user.
6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
6.5.2. 402 Payment Required
The 402 (Payment Required) status code is reserved for future use.
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
6.5.4. 404 Not Found
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.
A 404 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.5.5. 405 Method Not Allowed
The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource. The origin server MUST generate an Allow header field in a 405 response containing a list of the target resource’s currently supported methods.
A 405 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.5.6. 406 Not Acceptable
The 406 (Not Acceptable) status code indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request (Section 5.3), and the server is unwilling to supply a default representation.
The server SHOULD generate a payload containing a list of available representation characteristics and corresponding resource identifiers from which the user or user agent can choose the one most appropriate. A user agent MAY automatically select the most appropriate choice from that list. However, this specification does not define any standard for such automatic selection, as described in Section 6.4.1.
6.5.7. 408 Request Timeout
The 408 (Request Timeout) status code indicates that the server did not receive a complete request message within the time that it was prepared to wait. A server SHOULD send the «close» connection option (Section 6.1 of [RFC7230]) in the response, since 408 implies that the server has decided to close the connection rather than continue waiting. If the client has an outstanding request in transit, the client MAY repeat that request on a new connection.
6.5.8. 409 Conflict
The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict.
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the representation being PUT included changes to a resource that conflict with those made by an earlier (third-party) request, the origin server might use a 409 response to indicate that it can’t complete the request. In this case, the response representation would likely contain information useful for merging the differences based on the revision history.
6.5.9. 410 Gone
The 410 (Gone) status code indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent. If the origin server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) ought to be used instead.
The 410 response is primarily intended to assist the task of web maintenance by notifying the recipient that the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed. Such an event is common for limited-time, promotional services and for resources belonging to individuals no longer associated with the origin server’s site. It is not necessary to mark all permanently unavailable resources as «gone» or to keep the mark for any length of time — that is left to the discretion of the server owner.
A 410 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.5.10. 411 Length Required
The 411 (Length Required) status code indicates that the server refuses to accept the request without a defined Content-Length (Section 3.3.2 of [RFC7230]). The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message body in the request message.
6.5.11. 413 Payload Too Large
The 413 (Payload Too Large) status code indicates that the server is refusing to process a request because the request payload is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.
If the condition is temporary, the server SHOULD generate a Retry-After header field to indicate that it is temporary and after what time the client MAY try again.
6.5.12. 414 URI Too Long
The 414 (URI Too Long) status code indicates that the server is refusing to service the request because the request-target (Section 5.3 of [RFC7230]) is longer than the server is willing to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into a «black hole» of redirection (e.g., a redirected URI prefix that points to a suffix of itself) or when the server is under attack by a client attempting to exploit potential security holes.
A 414 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.5.13. 415 Unsupported Media Type
The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource. The format problem might be due to the request’s indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.
6.5.14. 417 Expectation Failed
The 417 (Expectation Failed) status code indicates that the expectation given in the request’s Expect header field (Section 5.1.1) could not be met by at least one of the inbound servers.
6.5.15. 426 Upgrade Required
The 426 (Upgrade Required) status code indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server MUST send an Upgrade header field in a 426 response to indicate the required protocol(s) (Section 6.7 of [RFC7230]).
Example:
HTTP/1.1 426 Upgrade Required
Upgrade: HTTP/3.0
Connection: Upgrade
Content-Length: 53
Content-Type: text/plain
This service requires use of the HTTP/3.0 protocol.
6.6. Server Error 5xx
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition. A user agent SHOULD display any included representation to the user. These response codes are applicable to any request method.
6.6.1. 500 Internal Server Error
The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
6.6.2. 501 Not Implemented
The 501 (Not Implemented) status code indicates that the server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
A 501 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
6.6.3. 502 Bad Gateway
The 502 (Bad Gateway) status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
6.6.4. 503 Service Unavailable
The 503 (Service Unavailable) status code indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. The server MAY send a Retry-After header field (Section 7.1.3) to suggest an appropriate amount of time for the client to wait before retrying the request.
6.6.5. 504 Gateway Timeout
The 504 (Gateway Timeout) status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
6.6.6. 505 HTTP Version Not Supported
The 505 (HTTP Version Not Supported) status code indicates that the server does not support, or refuses to support, the major version of HTTP that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in Section 2.6 of [RFC7230], other than with this error message. The server SHOULD generate a representation for the 505 response that describes why that version is not supported and what other protocols are supported by that server.
8. IANA Considerations
8.1. Method Registry
The «Hypertext Transfer Protocol (HTTP) Method Registry» defines the namespace for the request method token (Section 4). The method registry has been created and is now maintained at <http://www.iana.org/assignments/http-methods>.
8.1.1. Procedure
HTTP method registrations MUST include the following fields:
- Method Name (see Section 4)
- Safe («yes» or «no», see Section 4.2.1)
- Idempotent («yes» or «no», see Section 4.2.2)
- Pointer to specification text
Values to be added to this namespace require IETF Review (see [RFC5226], Section 4.1).
8.1.2. Considerations for New Methods
Standardized methods are generic; that is, they are potentially applicable to any resource, not just one particular media type, kind of resource, or application. As such, it is preferred that new methods be registered in a document that isn’t specific to a single application or data format, since orthogonal technologies deserve orthogonal specification.
Since message parsing (Section 3.3 of [RFC7230]) needs to be independent of method semantics (aside from responses to HEAD), definitions of new methods cannot change the parsing algorithm or prohibit the presence of a message body on either the request or the response message. Definitions of new methods can specify that only a zero-length message body is allowed by requiring a Content-Length header field with a value of «0».
A new method definition needs to indicate whether it is safe (Section 4.2.1), idempotent (Section 4.2.2), cacheable (Section 4.2.3), what semantics are to be associated with the payload body if any is present in the request and what refinements the method makes to header field or status code semantics. If the new method is cacheable, its definition ought to describe how, and under what conditions, a cache can store a response and use it to satisfy a subsequent request. The new method ought to describe whether it can be made conditional (Section 5.2) and, if so, how a server responds when the condition is false. Likewise, if the new method might have some use for partial response semantics ([RFC7233]), it ought to document this, too.
8.1.3. Registrations
The «Hypertext Transfer Protocol (HTTP) Method Registry» has been populated with the registrations below:
Method | Safe | Idempotent | Reference |
---|---|---|---|
CONNECT | no | no | Section 4.3.6 |
DELETE | no | yes | Section 4.3.5 |
GET | yes | yes | Section 4.3.1 |
HEAD | yes | yes | Section 4.3.2 |
OPTIONS | yes | yes | Section 4.3.7 |
POST | no | no | Section 4.3.3 |
PUT | no | yes | Section 4.3.4 |
TRACE | yes | yes | Section 4.3.8 |
8.2. Status Code Registry
The «Hypertext Transfer Protocol (HTTP) Status Code Registry» defines the namespace for the response status-code token (Section 6). The status code registry is maintained at <http://www.iana.org/assignments/http-status-codes>.
This section replaces the registration procedure for HTTP Status Codes previously defined in Section 7.1 of [RFC2817].
8.2.1. Procedure
A registration MUST include the following fields:
- Status Code (3 digits)
- Short Description
- Pointer to specification text
Values to be added to the HTTP status code namespace require IETF Review (see [RFC5226], Section 4.1).
8.2.2. Considerations for New Status Codes
When it is necessary to express semantics for a response that are not defined by current status codes, a new status code can be registered. Status codes are generic; they are potentially applicable to any resource, not just one particular media type, kind of resource, or application of HTTP. As such, it is preferred that new status codes be registered in a document that isn’t specific to a single application.
New status codes are required to fall under one of the categories defined in Section 6. To allow existing parsers to process the response message, new status codes cannot disallow a payload, although they can mandate a zero-length payload body.
Proposals for new status codes that are not yet widely deployed ought to avoid allocating a specific number for the code until there is clear consensus that it will be registered; instead, early drafts can use a notation such as «4NN», or «3N0» .. «3N9», to indicate the class of the proposed status code(s) without consuming a number prematurely.
The definition of a new status code ought to explain the request conditions that would cause a response containing that status code (e.g., combinations of request header fields and/or method(s)) along with any dependencies on response header fields (e.g., what fields are required, what fields can modify the semantics, and what header field semantics are further refined when used with the new status code).
The definition of a new status code ought to specify whether or not it is cacheable. Note that all status codes can be cached if the response they occur in has explicit freshness information; however, status codes that are defined as being cacheable are allowed to be cached without explicit freshness information. Likewise, the definition of a status code can place constraints upon cache behavior. See [RFC7234] for more information.
Finally, the definition of a new status code ought to indicate whether the payload has any implied association with an identified resource (Section 3.1.4.1).
8.2.3. Registrations
The status code registry has been updated with the registrations below:
Value | Description | Reference |
---|---|---|
100 | Continue | Section 6.2.1 |
101 | Switching Protocols | Section 6.2.2 |
200 | OK | Section 6.3.1 |
201 | Created | Section 6.3.2 |
202 | Accepted | Section 6.3.3 |
203 | Non-Authoritative Information | Section 6.3.4 |
204 | No Content | Section 6.3.5 |
205 | Reset Content | Section 6.3.6 |
300 | Multiple Choices | Section 6.4.1 |
301 | Moved Permanently | Section 6.4.2 |
302 | Found | Section 6.4.3 |
303 | See Other | Section 6.4.4 |
305 | Use Proxy | Section 6.4.5 |
306 | (Unused) | Section 6.4.6 |
307 | Temporary Redirect | Section 6.4.7 |
400 | Bad Request | Section 6.5.1 |
402 | Payment Required | Section 6.5.2 |
403 | Forbidden | Section 6.5.3 |
404 | Not Found | Section 6.5.4 |
405 | Method Not Allowed | Section 6.5.5 |
406 | Not Acceptable | Section 6.5.6 |
408 | Request Timeout | Section 6.5.7 |
409 | Conflict | Section 6.5.8 |
410 | Gone | Section 6.5.9 |
411 | Length Required | Section 6.5.10 |
413 | Payload Too Large | Section 6.5.11 |
414 | URI Too Long | Section 6.5.12 |
415 | Unsupported Media Type | Section 6.5.13 |
417 | Expectation Failed | Section 6.5.14 |
426 | Upgrade Required | Section 6.5.15 |
500 | Internal Server Error | Section 6.6.1 |
501 | Not Implemented | Section 6.6.2 |
502 | Bad Gateway | Section 6.6.3 |
503 | Service Unavailable | Section 6.6.4 |
504 | Gateway Timeout | Section 6.6.5 |
505 | HTTP Version Not Supported | Section 6.6.6 |
8.4. Content Coding Registry
8.4.1. Procedure
Content coding registrations MUST include the following fields:
- Name
- Description
- Pointer to specification text
Names of content codings MUST NOT overlap with names of transfer codings (Section 4 of [RFC7230]), unless the encoding transformation is identical (as is the case for the compression codings defined in Section 4.2 of [RFC7230]).
Values to be added to this namespace require IETF Review (see Section 4.1 of [RFC5226]) and MUST conform to the purpose of content coding defined in this section.
8.4.2. Registrations
The «HTTP Content Coding Registry» has been updated with the registrations below:
Name | Description | Reference |
---|---|---|
identity | Reserved (synonym for «no encoding» in Accept-Encoding) | Section 5.3.4 |
9. Security Considerations
This section is meant to inform developers, information providers, and users of known security concerns relevant to HTTP semantics and its use for transferring information over the Internet. Considerations related to message syntax, parsing, and routing are discussed in Section 9 of [RFC7230].
The list of considerations below is not exhaustive. Most security concerns related to HTTP semantics are about securing server-side applications (code behind the HTTP interface), securing user agent processing of payloads received via HTTP, or secure use of the Internet in general, rather than security of the protocol. Various organizations maintain topical information and links to current research on Web application security (e.g., [OWASP]).
9.1. Attacks Based on File and Path Names
Origin servers frequently make use of their local file system to manage the mapping from effective request URI to resource representations. Most file systems are not designed to protect against malicious file or path names. Therefore, an origin server needs to avoid accessing names that have a special significance to the system when mapping the request target to files, folders, or directories.
For example, UNIX, Microsoft Windows, and other operating systems use «..» as a path component to indicate a directory level above the current one, and they use specially named paths or file names to send data to system devices. Similar naming conventions might exist within other types of storage systems. Likewise, local storage systems have an annoying tendency to prefer user-friendliness over security when handling invalid or unexpected characters, recomposition of decomposed characters, and case-normalization of case-insensitive names.
Attacks based on such special names tend to focus on either denial-of-service (e.g., telling the server to read from a COM port) or disclosure of configuration and source files that are not meant to be served.
9.2. Attacks Based on Command, Code, or Query Injection
Origin servers often use parameters within the URI as a means of identifying system services, selecting database entries, or choosing a data source. However, data received in a request cannot be trusted. An attacker could construct any of the request data elements (method, request-target, header fields, or body) to contain data that might be misinterpreted as a command, code, or query when passed through a command invocation, language interpreter, or database interface.
For example, SQL injection is a common attack wherein additional query language is inserted within some part of the request-target or header fields (e.g., Host, Referer, etc.). If the received data is used directly within a SELECT statement, the query language might be interpreted as a database command instead of a simple string value. This type of implementation vulnerability is extremely common, in spite of being easy to prevent.
In general, resource implementations ought to avoid use of request data in contexts that are processed or interpreted as instructions. Parameters ought to be compared to fixed strings and acted upon as a result of that comparison, rather than passed through an interface that is not prepared for untrusted data. Received data that isn’t based on fixed parameters ought to be carefully filtered or encoded to avoid being misinterpreted.
Similar considerations apply to request data when it is stored and later processed, such as within log files, monitoring tools, or when included within a data format that allows embedded scripts.
9.3. Disclosure of Personal Information
Clients are often privy to large amounts of personal information, including both information provided by the user to interact with resources (e.g., the user’s name, location, mail address, passwords, encryption keys, etc.) and information about the user’s browsing activity over time (e.g., history, bookmarks, etc.). Implementations need to prevent unintentional disclosure of personal information.
9.4. Disclosure of Sensitive Information in URIs
URIs are intended to be shared, not secured, even when they identify secure resources. URIs are often shown on displays, added to templates when a page is printed, and stored in a variety of unprotected bookmark lists. It is therefore unwise to include information within a URI that is sensitive, personally identifiable, or a risk to disclose.
Authors of services ought to avoid GET-based forms for the submission of sensitive data because that data will be placed in the request-target. Many existing servers, proxies, and user agents log or display the request-target in places where it might be visible to third parties. Such services ought to use POST-based form submission instead.
Since the Referer header field tells a target site about the context that resulted in a request, it has the potential to reveal information about the user’s immediate browsing history and any personal information that might be found in the referring resource’s URI. Limitations on the Referer header field are described in Section 5.5.2 to address some of its security considerations.
9.5. Disclosure of Fragment after Redirects
Although fragment identifiers used within URI references are not sent in requests, implementers ought to be aware that they will be visible to the user agent and any extensions or scripts running as a result of the response. In particular, when a redirect occurs and the original request’s fragment identifier is inherited by the new reference in Location (Section 7.1.2), this might have the effect of disclosing one site’s fragment to another site. If the first site uses personal information in fragments, it ought to ensure that redirects to other sites include a (possibly empty) fragment component in order to block that inheritance.
9.6. Disclosure of Product Information
The User-Agent (Section 5.5.3), Via (Section 5.7.1 of [RFC7230]), and Server (Section 7.4.2) header fields often reveal information about the respective sender’s software systems. In theory, this can make it easier for an attacker to exploit known security holes; in practice, attackers tend to try all potential holes regardless of the apparent software versions being used.
Proxies that serve as a portal through a network firewall ought to take special precautions regarding the transfer of header information that might identify hosts behind the firewall. The Via header field allows intermediaries to replace sensitive machine names with pseudonyms.
9.7. Browser Fingerprinting
Browser fingerprinting is a set of techniques for identifying a specific user agent over time through its unique set of characteristics. These characteristics might include information related to its TCP behavior, feature capabilities, and scripting environment, though of particular interest here is the set of unique characteristics that might be communicated via HTTP. Fingerprinting is considered a privacy concern because it enables tracking of a user agent’s behavior over time without the corresponding controls that the user might have over other forms of data collection (e.g., cookies). Many general-purpose user agents (i.e., Web browsers) have taken steps to reduce their fingerprints.
There are a number of request header fields that might reveal information to servers that is sufficiently unique to enable fingerprinting. The From header field is the most obvious, though it is expected that From will only be sent when self-identification is desired by the user. Likewise, Cookie header fields are deliberately designed to enable re-identification, so fingerprinting concerns only apply to situations where cookies are disabled or restricted by the user agent’s configuration.
The User-Agent header field might contain enough information to uniquely identify a specific device, usually when combined with other characteristics, particularly if the user agent sends excessive details about the user’s system or extensions. However, the source of unique information that is least expected by users is proactive negotiation (Section 5.3), including the Accept, Accept-Charset, Accept-Encoding, and Accept-Language header fields.
In addition to the fingerprinting concern, detailed use of the Accept-Language header field can reveal information the user might consider to be of a private nature. For example, understanding a given language set might be strongly correlated to membership in a particular ethnic group. An approach that limits such loss of privacy would be for a user agent to omit the sending of Accept-Language except for sites that have been whitelisted, perhaps via interaction after detecting a Vary header field that indicates language negotiation might be useful.
In environments where proxies are used to enhance privacy, user agents ought to be conservative in sending proactive negotiation header fields. General-purpose user agents that provide a high degree of header field configurability ought to inform users about the loss of privacy that might result if too much detail is provided. As an extreme privacy measure, proxies could filter the proactive negotiation header fields in relayed requests.
10. Acknowledgments
11. References
11.1. Normative References
- [RFC2045]
- Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies”, RFC 2045, November 1996.
- [RFC2046]
- Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types”, RFC 2046, November 1996.
- [RFC2119]
- Bradner, S., “Key words for use in RFCs to Indicate Requirement Levels”, BCP 14, RFC 2119, March 1997.
- [RFC3986]
- Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax”, STD 66, RFC 3986, January 2005.
- [RFC4647]
- Phillips, A., Ed. and M. Davis, Ed., “Matching of Language Tags”, BCP 47, RFC 4647, September 2006.
- [RFC5234]
- Crocker, D., Ed. and P. Overell, “Augmented BNF for Syntax Specifications: ABNF”, STD 68, RFC 5234, January 2008.
- [RFC5646]
- Phillips, A., Ed. and M. Davis, Ed., “Tags for Identifying Languages”, BCP 47, RFC 5646, September 2009.
- [RFC6365]
- Hoffman, P. and J. Klensin, “Terminology Used in Internationalization in the IETF”, BCP 166, RFC 6365, September 2011.
- [RFC7230]
- Fielding, R., Ed. and J. Reschke, Ed., “Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing”, RFC 7230, June 2014.
- [RFC7232]
- Fielding, R., Ed. and J. Reschke, Ed., “Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests”, RFC 7232, June 2014.
- [RFC7233]
- Fielding, R., Ed., Lafon, Y., Ed., and J. Reschke, Ed., “Hypertext Transfer Protocol (HTTP/1.1): Range Requests”, RFC 7233, June 2014.
- [RFC7234]
- Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., “Hypertext Transfer Protocol (HTTP/1.1): Caching”, RFC 7234, June 2014.
- [RFC7235]
- Fielding, R., Ed. and J. Reschke, Ed., “Hypertext Transfer Protocol (HTTP/1.1): Authentication”, RFC 7235, June 2014.
11.2. Informative References
- [BCP13]
- Freed, N., Klensin, J., and T. Hansen, “Media Type Specifications and Registration Procedures”, BCP 13, RFC 6838, January 2013.
- [BCP178]
- Saint-Andre, P., Crocker, D., and M. Nottingham, “Deprecating the «X-» Prefix and Similar Constructs in Application Protocols”, BCP 178, RFC 6648, June 2012.
- [BCP90]
- Klyne, G., Nottingham, M., and J. Mogul, “Registration Procedures for Message Header Fields”, BCP 90, RFC 3864, September 2004.
- [OWASP]
- van der Stock, A., Ed., “A Guide to Building Secure Web Applications and Web Services”, The Open Web Application Security Project (OWASP) 2.0.1, July 2005, <https://www.owasp.org/>.
- [REST]
- Fielding, R., “Architectural Styles and the Design of Network-based Software Architectures”, Doctoral Dissertation, University of California, Irvine, September 2000, <http://roy.gbiv.com/pubs/dissertation/top.htm>.
- [RFC1945]
- Berners-Lee, T., Fielding, R., and H. Nielsen, “Hypertext Transfer Protocol — HTTP/1.0”, RFC 1945, May 1996.
- [RFC2049]
- Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples”, RFC 2049, November 1996.
- [RFC2068]
- Fielding, R., Gettys, J., Mogul, J., Nielsen, H., and T. Berners-Lee, “Hypertext Transfer Protocol — HTTP/1.1”, RFC 2068, January 1997.
- [RFC2295]
- Holtman, K. and A. Mutz, “Transparent Content Negotiation in HTTP”, RFC 2295, March 1998.
- [RFC2388]
- Masinter, L., “Returning Values from Forms: multipart/form-data”, RFC 2388, August 1998.
- [RFC2557]
- Palme, F., Hopmann, A., Shelness, N., and E. Stefferud, “MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)”, RFC 2557, March 1999.
- [RFC2616]
- Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, “Hypertext Transfer Protocol — HTTP/1.1”, RFC 2616, June 1999.
- [RFC2774]
- Frystyk, H., Leach, P., and S. Lawrence, “An HTTP Extension Framework”, RFC 2774, February 2000.
- [RFC2817]
- Khare, R. and S. Lawrence, “Upgrading to TLS Within HTTP/1.1”, RFC 2817, May 2000.
- [RFC2978]
- Freed, N. and J. Postel, “IANA Charset Registration Procedures”, BCP 19, RFC 2978, October 2000.
- [RFC5226]
- Narten, T. and H. Alvestrand, “Guidelines for Writing an IANA Considerations Section in RFCs”, BCP 26, RFC 5226, May 2008.
- [RFC5246]
- Dierks, T. and E. Rescorla, “The Transport Layer Security (TLS) Protocol Version 1.2”, RFC 5246, August 2008.
- [RFC5322]
- Resnick, P., “Internet Message Format”, RFC 5322, October 2008.
- [RFC5789]
- Dusseault, L. and J. Snell, “PATCH Method for HTTP”, RFC 5789, March 2010.
- [RFC5905]
- Mills, D., Martin, J., Ed., Burbank, J., and W. Kasch, “Network Time Protocol Version 4: Protocol and Algorithms Specification”, RFC 5905, June 2010.
- [RFC5987]
- Reschke, J., “Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters”, RFC 5987, August 2010.
- [RFC5988]
- Nottingham, M., “Web Linking”, RFC 5988, October 2010.
- [RFC6265]
- Barth, A., “HTTP State Management Mechanism”, RFC 6265, April 2011.
- [RFC6266]
- Reschke, J., “Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)”, RFC 6266, June 2011.
- [RFC7238]
- Reschke, J., “The Hypertext Transfer Protocol (HTTP) Status Code 308 (Permanent Redirect)”, RFC 7238, June 2014.
Appendix A. Differences between HTTP and MIME
HTTP/1.1 uses many of the constructs defined for the Internet Message Format [RFC5322] and the Multipurpose Internet Mail Extensions (MIME) [RFC2045] to allow a message body to be transmitted in an open variety of representations and with extensible header fields. However, RFC 2045 is focused only on email; applications of HTTP have many characteristics that differ from email; hence, HTTP has features that differ from MIME. These differences were carefully chosen to optimize performance over binary connections, to allow greater freedom in the use of new media types, to make date comparisons easier, and to acknowledge the practice of some early HTTP servers and clients.
This appendix describes specific areas where HTTP differs from MIME. Proxies and gateways to and from strict MIME environments need to be aware of these differences and provide the appropriate conversions where necessary.
A.1. MIME-Version
HTTP is not a MIME-compliant protocol. However, messages can include a single MIME-Version header field to indicate what version of the MIME protocol was used to construct the message. Use of the MIME-Version header field indicates that the message is in full conformance with the MIME protocol (as defined in [RFC2045]). Senders are responsible for ensuring full conformance (where possible) when exporting HTTP messages to strict MIME environments.
A.2. Conversion to Canonical Form
MIME requires that an Internet mail body part be converted to canonical form prior to being transferred, as described in Section 4 of [RFC2049]. Section 3.1.1.3 of this document describes the forms allowed for subtypes of the «text» media type when transmitted over HTTP. [RFC2046] requires that content with a type of «text» represent line breaks as CRLF and forbids the use of CR or LF outside of line break sequences. HTTP allows CRLF, bare CR, and bare LF to indicate a line break within text content.
A proxy or gateway from HTTP to a strict MIME environment ought to translate all line breaks within the text media types described in Section 3.1.1.3 of this document to the RFC 2049 canonical form of CRLF. Note, however, this might be complicated by the presence of a Content-Encoding and by the fact that HTTP allows the use of some charsets that do not use octets 13 and 10 to represent CR and LF, respectively.
Conversion will break any cryptographic checksums applied to the original content unless the original content is already in canonical form. Therefore, the canonical form is recommended for any content that uses such checksums in HTTP.
A.3. Conversion of Date Formats
HTTP/1.1 uses a restricted set of date formats (Section 7.1.1.1) to simplify the process of date comparison. Proxies and gateways from other protocols ought to ensure that any Date header field present in a message conforms to one of the HTTP/1.1 formats and rewrite the date if necessary.
A.4. Conversion of Content-Encoding
MIME does not include any concept equivalent to HTTP/1.1’s Content-Encoding header field. Since this acts as a modifier on the media type, proxies and gateways from HTTP to MIME-compliant protocols ought to either change the value of the Content-Type header field or decode the representation before forwarding the message. (Some experimental applications of Content-Type for Internet mail have used a media-type parameter of «;conversions=<content-coding>» to perform a function equivalent to Content-Encoding. However, this parameter is not part of the MIME standards).
A.5. Conversion of Content-Transfer-Encoding
HTTP does not use the Content-Transfer-Encoding field of MIME. Proxies and gateways from MIME-compliant protocols to HTTP need to remove any Content-Transfer-Encoding prior to delivering the response message to an HTTP client.
Proxies and gateways from HTTP to MIME-compliant protocols are responsible for ensuring that the message is in the correct format and encoding for safe transport on that protocol, where «safe transport» is defined by the limitations of the protocol being used. Such a proxy or gateway ought to transform and label the data with an appropriate Content-Transfer-Encoding if doing so will improve the likelihood of safe transport over the destination protocol.
A.6. MHTML and Line Length Limitations
HTTP implementations that share code with MHTML [RFC2557] implementations need to be aware of MIME line length limitations. Since HTTP does not have this limitation, HTTP does not fold long lines. MHTML messages being transported by HTTP follow all conventions of MHTML, including line length limitations and folding, canonicalization, etc., since HTTP transfers message-bodies as payload and, aside from the «multipart/byteranges» type (Appendix A of [RFC7233]), does not interpret the content or any MIME header lines that might be contained therein.
Appendix B. Changes from RFC 2616
The primary changes in this revision have been editorial in nature: extracting the messaging syntax and partitioning HTTP semantics into separate documents for the core features, conditional requests, partial requests, caching, and authentication. The conformance language has been revised to clearly target requirements and the terminology has been improved to distinguish payload from representations and representations from resources.
A new requirement has been added that semantics embedded in a URI be disabled when those semantics are inconsistent with the request method, since this is a common cause of interoperability failure. (Section 2)
An algorithm has been added for determining if a payload is associated with a specific identifier. (Section 3.1.4.1)
The default charset of ISO-8859-1 for text media types has been removed; the default is now whatever the media type definition says. Likewise, special treatment of ISO-8859-1 has been removed from the Accept-Charset header field. (Section 3.1.1.3 and Section 5.3.3)
The definition of Content-Location has been changed to no longer affect the base URI for resolving relative URI references, due to poor implementation support and the undesirable effect of potentially breaking relative links in content-negotiated resources. (Section 3.1.4.2)
To be consistent with the method-neutral parsing algorithm of [RFC7230], the definition of GET has been relaxed so that requests can have a body, even though a body has no meaning for GET. (Section 4.3.1)
Servers are no longer required to handle all Content-* header fields and use of Content-Range has been explicitly banned in PUT requests. (Section 4.3.4)
Definition of the CONNECT method has been moved from [RFC2817] to this specification. (Section 4.3.6)
The OPTIONS and TRACE request methods have been defined as being safe. (Section 4.3.7 and Section 4.3.8)
The Expect header field’s extension mechanism has been removed due to widely-deployed broken implementations. (Section 5.1.1)
The Max-Forwards header field has been restricted to the OPTIONS and TRACE methods; previously, extension methods could have used it as well. (Section 5.1.2)
The «about:blank» URI has been suggested as a value for the Referer header field when no referring URI is applicable, which distinguishes that case from others where the Referer field is not sent or has been removed. (Section 5.5.2)
The following status codes are now cacheable (that is, they can be stored and reused by a cache without explicit freshness information present): 204, 404, 405, 414, 501. (Section 6)
The 201 (Created) status description has been changed to allow for the possibility that more than one resource has been created. (Section 6.3.2)
The definition of 203 (Non-Authoritative Information) has been broadened to include cases of payload transformations as well. (Section 6.3.4)
The set of request methods that are safe to automatically redirect is no longer closed; user agents are able to make that determination based upon the request method semantics. The redirect status codes 301, 302, and 307 no longer have normative requirements on response payloads and user interaction. (Section 6.4)
The status codes 301 and 302 have been changed to allow user agents to rewrite the method from POST to GET. (Sections 6.4.2 and 6.4.3)
The description of the 303 (See Other) status code has been changed to allow it to be cached if explicit freshness information is given, and a specific definition has been added for a 303 response to GET. (Section 6.4.4)
The 305 (Use Proxy) status code has been deprecated due to security concerns regarding in-band configuration of a proxy. (Section 6.4.5)
The 400 (Bad Request) status code has been relaxed so that it isn’t limited to syntax errors. (Section 6.5.1)
The 426 (Upgrade Required) status code has been incorporated from [RFC2817]. (Section 6.5.15)
The target of requirements on HTTP-date and the Date header field have been reduced to those systems generating the date, rather than all systems sending a date. (Section 7.1.1)
The syntax of the Location header field has been changed to allow all URI references, including relative references and fragments, along with some clarifications as to when use of fragments would not be appropriate. (Section 7.1.2)
Allow has been reclassified as a response header field, removing the option to specify it in a PUT request. Requirements relating to the content of Allow have been relaxed; correspondingly, clients are not required to always trust its value. (Section 7.4.1)
A Method Registry has been defined. (Section 8.1)
The Status Code Registry has been redefined by this specification; previously, it was defined in Section 7.1 of [RFC2817]. (Section 8.2)
Registration of content codings has been changed to require IETF Review. (Section 8.4)
The Content-Disposition header field has been removed since it is now defined by [RFC6266].
The Content-MD5 header field has been removed because it was inconsistently implemented with respect to partial responses.
Appendix C. Imported ABNF
The following core rules are included by reference, as defined in Appendix B.1 of [RFC5234]: ALPHA (letters), CR (carriage return), CRLF (CR LF), CTL (controls), DIGIT (decimal 0-9), DQUOTE (double quote), HEXDIG (hexadecimal 0-9/A-F/a-f), HTAB (horizontal tab), LF (line feed), OCTET (any 8-bit sequence of data), SP (space), and VCHAR (any visible US-ASCII character).
The rules below are defined in [RFC7230]:
BWS = <BWS, see [RFC7230], Section 3.2.3> OWS = <OWS, see [RFC7230], Section 3.2.3> RWS = <RWS, see [RFC7230], Section 3.2.3> URI-reference = <URI-reference, see [RFC7230], Section 2.7> absolute-URI = <absolute-URI, see [RFC7230], Section 2.7> comment = <comment, see [RFC7230], Section 3.2.6> field-name = <comment, see [RFC7230], Section 3.2> partial-URI = <partial-URI, see [RFC7230], Section 2.7> quoted-string = <quoted-string, see [RFC7230], Section 3.2.6> token = <token, see [RFC7230], Section 3.2.6>
Appendix D. Collected ABNF
In the collected ABNF below, list rules are expanded as per Section 1.2 of [RFC7230].
Accept = [ ( "," / ( media-range [ accept-params ] ) ) *( OWS "," [ OWS ( media-range [ accept-params ] ) ] ) ] Accept-Charset = *( "," OWS ) ( ( charset / "*" ) [ weight ] ) *( OWS "," [ OWS ( ( charset / "*" ) [ weight ] ) ] ) Accept-Encoding = [ ( "," / ( codings [ weight ] ) ) *( OWS "," [ OWS ( codings [ weight ] ) ] ) ] Accept-Language = *( "," OWS ) ( language-range [ weight ] ) *( OWS "," [ OWS ( language-range [ weight ] ) ] ) Allow = [ ( "," / method ) *( OWS "," [ OWS method ] ) ] BWS = <BWS, see [RFC7230], Section 3.2.3> Content-Encoding = *( "," OWS ) content-coding *( OWS "," [ OWS content-coding ] ) Content-Language = *( "," OWS ) language-tag *( OWS "," [ OWS language-tag ] ) Content-Location = absolute-URI / partial-URI Content-Type = media-type Date = HTTP-date Expect = "100-continue" From = mailbox GMT = %x47.4D.54 ; GMT HTTP-date = IMF-fixdate / obs-date IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT Location = URI-reference Max-Forwards = 1*DIGIT OWS = <OWS, see [RFC7230], Section 3.2.3> RWS = <RWS, see [RFC7230], Section 3.2.3> Referer = absolute-URI / partial-URI Retry-After = HTTP-date / delay-seconds Server = product *( RWS ( product / comment ) ) URI-reference = <URI-reference, see [RFC7230], Section 2.7> User-Agent = product *( RWS ( product / comment ) ) Vary = "*" / ( *( "," OWS ) field-name *( OWS "," [ OWS field-name ] ) ) absolute-URI = <absolute-URI, see [RFC7230], Section 2.7> accept-ext = OWS ";" OWS token [ "=" ( token / quoted-string ) ] accept-params = weight *accept-ext asctime-date = day-name SP date3 SP time-of-day SP year charset = token codings = content-coding / "identity" / "*" comment = <comment, see [RFC7230], Section 3.2.6> content-coding = token date1 = day SP month SP year date2 = day "-" month "-" 2DIGIT date3 = month SP ( 2DIGIT / ( SP DIGIT ) ) day = 2DIGIT day-name = %x4D.6F.6E ; Mon / %x54.75.65 ; Tue / %x57.65.64 ; Wed / %x54.68.75 ; Thu / %x46.72.69 ; Fri / %x53.61.74 ; Sat / %x53.75.6E ; Sun day-name-l = %x4D.6F.6E.64.61.79 ; Monday / %x54.75.65.73.64.61.79 ; Tuesday / %x57.65.64.6E.65.73.64.61.79 ; Wednesday / %x54.68.75.72.73.64.61.79 ; Thursday / %x46.72.69.64.61.79 ; Friday / %x53.61.74.75.72.64.61.79 ; Saturday / %x53.75.6E.64.61.79 ; Sunday delay-seconds = 1*DIGIT field-name = <comment, see [RFC7230], Section 3.2> hour = 2DIGIT language-range = <language-range, see [RFC4647], Section 2.1> language-tag = <Language-Tag, see [RFC5646], Section 2.1> mailbox = <mailbox, see [RFC5322], Section 3.4> media-range = ( "*/*" / ( type "/*" ) / ( type "/" subtype ) ) *( OWS ";" OWS parameter ) media-type = type "/" subtype *( OWS ";" OWS parameter ) method = token minute = 2DIGIT month = %x4A.61.6E ; Jan / %x46.65.62 ; Feb / %x4D.61.72 ; Mar / %x41.70.72 ; Apr / %x4D.61.79 ; May / %x4A.75.6E ; Jun / %x4A.75.6C ; Jul / %x41.75.67 ; Aug / %x53.65.70 ; Sep / %x4F.63.74 ; Oct / %x4E.6F.76 ; Nov / %x44.65.63 ; Dec obs-date = rfc850-date / asctime-date parameter = token "=" ( token / quoted-string ) partial-URI = <partial-URI, see [RFC7230], Section 2.7> product = token [ "/" product-version ] product-version = token quoted-string = <quoted-string, see [RFC7230], Section 3.2.6> qvalue = ( "0" [ "." *3DIGIT ] ) / ( "1" [ "." *3"0" ] ) rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT second = 2DIGIT subtype = token time-of-day = hour ":" minute ":" second token = <token, see [RFC7230], Section 3.2.6> type = token weight = OWS ";" OWS "q=" qvalue year = 4DIGIT
Index
1 2 3 4 5 A B C D E F G H I L M O P R S T U V X
- 1
- 100 Continue (status code) 6.1, 6.2.1, 8.2.3
- 100-continue (expect value) 5.1.1
- 101 Switching Protocols (status code) 6.1, 6.2.2, 8.2.3
- 1xx Informational (status code class) 6.2
- 2
- 200 OK (status code) 6.1, 6.3.1, 8.2.3
- 201 Created (status code) 6.1, 6.3.2, 8.2.3, B
- 202 Accepted (status code) 6.1, 6.3.3, 8.2.3
- 203 Non-Authoritative Information (status code) 6.1, 6.3.4, 8.2.3, B
- 204 No Content (status code) 6.1, 6.3.5, 8.2.3
- 205 Reset Content (status code) 6.1, 6.3.6, 8.2.3
- 2xx Successful (status code class) 6.3
- 3
- 300 Multiple Choices (status code) 6.1, 6.4.1, 6.5.6, 8.2.3
- 301 Moved Permanently (status code) 6.1, 6.4.2, 8.2.3, B
- 302 Found (status code) 6.1, 6.4.3, 8.2.3, B
- 303 See Other (status code) 6.1, 6.4.4, 8.2.3, B
- 305 Use Proxy (status code) 6.1, 6.4.5, 8.2.3, B
- 306 (Unused) (status code) 6.4.6, 8.2.3
- 307 Temporary Redirect (status code) 6.1, 6.4.7, 8.2.3
- 3xx Redirection (status code class) 6.4, B
- 4
- 400 Bad Request (status code) 6.1, 6.5.1, 8.2.3, B
- 402 Payment Required (status code) 6.1, 6.5.2, 8.2.3
- 403 Forbidden (status code) 6.1, 6.5.3, 8.2.3
- 404 Not Found (status code) 6.1, 6.5.4, 8.2.3
- 405 Method Not Allowed (status code) 6.1, 6.5.5, 8.2.3
- 406 Not Acceptable (status code) 6.1, 6.5.6, 8.2.3
- 408 Request Timeout (status code) 6.1, 6.5.7, 8.2.3
- 409 Conflict (status code) 6.1, 6.5.8, 8.2.3
- 410 Gone (status code) 6.1, 6.5.9, 8.2.3
- 411 Length Required (status code) 6.1, 6.5.10, 8.2.3
- 413 Payload Too Large (status code) 6.1, 6.5.11, 8.2.3
- 414 URI Too Long (status code) 6.1, 6.5.12, 8.2.3
- 415 Unsupported Media Type (status code) 6.1, 6.5.13, 8.2.3
- 417 Expectation Failed (status code) 6.1, 6.5.14, 8.2.3
- 426 Upgrade Required (status code) 6.1, 6.5.15, 8.2.3, B
- 4xx Client Error (status code class) 6.5
- 5
- 500 Internal Server Error (status code) 6.1, 6.6.1, 8.2.3
- 501 Not Implemented (status code) 6.1, 6.6.2, 8.2.3
- 502 Bad Gateway (status code) 6.1, 6.6.3, 8.2.3
- 503 Service Unavailable (status code) 6.1, 6.6.4, 8.2.3
- 504 Gateway Timeout (status code) 6.1, 6.6.5, 8.2.3
- 505 HTTP Version Not Supported (status code) 6.1, 6.6.6, 8.2.3
- 5xx Server Error (status code class) 6.6
- A
- Accept header field 3.1.1.1, 5.3, 5.3.2, 8.3.2
- Accept-Charset header field 5.3, 5.3.3, 8.3.2, B
- Accept-Encoding header field 3.1.2.1, 5.3, 5.3.4, 8.3.2, 8.4.2
- Accept-Language header field 3.1.3.1, 5.3, 5.3.5, 8.3.2
- Allow header field 4.1, 7.4, 7.4.1, 8.3.2, B
- B
- BCP13 3.1.1.1, 11.2
- BCP178 8.3.1, 11.2
- BCP90 8.3, 8.3.1, 11.2
- C
- cacheable 4.2.3
- compress (content coding) 3.1.2.1
- conditional request 5.2
- CONNECT method 4.1, 4.3.6, 8.1.3, B
- content coding 3.1.2.1
- content negotiation 1
- Content-Encoding header field 3.1, 3.1.2.1, 3.1.2.2, 8.3.2
- Content-Language header field 3.1, 3.1.3.2, 8.3.2
- Content-Location header field 3.1, 3.1.4.2, 4.3.3, 7.1.2, 8.3.2, B
- Content-Transfer-Encoding header field A.5
- Content-Type header field 3.1, 3.1.1.1, 3.1.1.5, 8.3.1, 8.3.2
- D
- Date header field 3.3, 7.1, 7.1.1.2, 8.3.2
- deflate (content coding) 3.1.2.1
- DELETE method 4.1, 4.3.5, 8.1.3
- E
- Expect header field 5.1, 5.1.1, 6.2.1, 6.5.14, 8.3.2, B
- F
- From header field 5.5, 5.5.1, 8.3.2
- G
- GET method 3, 3.1.4.2, 3.3, 4.1, 4.3.1, 8.1.3, B
- Grammar
- Accept 5.3.2
- Accept-Charset 5.3.3
- Accept-Encoding 5.3.4
- accept-ext 5.3.2
- Accept-Language 5.3.5
- accept-params 5.3.2
- Allow 7.4.1
- asctime-date 7.1.1.1
- charset 3.1.1.2
- codings 5.3.4
- content-coding 3.1.2.1
- Content-Encoding 3.1.2.2
- Content-Language 3.1.3.2
- Content-Location 3.1.4.2
- Content-Type 3.1.1.5
- Date 7.1.1.2
- date1 7.1.1.1
- day 7.1.1.1
- day-name 7.1.1.1
- day-name-l 7.1.1.1
- delay-seconds 7.1.3
- Expect 5.1.1
- From 5.5.1
- GMT 7.1.1.1
- hour 7.1.1.1
- HTTP-date 7.1.1.1
- IMF-fixdate 7.1.1.1
- language-range 5.3.5
- language-tag 3.1.3.1
- Location 7.1.2
- Max-Forwards 5.1.2
- media-range 5.3.2
- media-type 3.1.1.1
- method 4.1
- minute 7.1.1.1
- month 7.1.1.1
- obs-date 7.1.1.1
- parameter 3.1.1.1
- product 5.5.3
- product-version 5.5.3
- qvalue 5.3.1
- Referer 5.5.2
- Retry-After 7.1.3
- rfc850-date 7.1.1.1
- second 7.1.1.1
- Server 7.4.2
- subtype 3.1.1.1
- time-of-day 7.1.1.1
- type 3.1.1.1
- User-Agent 5.5.3
- Vary 7.1.4
- weight 5.3.1
- year 7.1.1.1
- gzip (content coding) 3.1.2.1
- H
- HEAD method 3.1.4.2, 4.1, 4.3.2, 8.1.3
- I
- idempotent 4.2.2
- L
- Location header field 4.3.3, 6.4, 7.1, 7.1.2, 8.3.2, 9.5, B
- M
- Max-Forwards header field 4.3.7, 4.3.8, 5.1, 5.1.2, 8.3.2, B
- MIME-Version header field 8.3.2, A.1
- O
- OPTIONS method 4.1, 4.3.7, 5.1.2, 8.1.3, B, B, B
- OWASP 9, 11.2
- P
- payload 3.3
- POST method 3.1.4.2, 3.3, 4.1, 4.3.3, 8.1.3
- PUT method 3.1.4.2, 3.3, 4.1, 4.3.4, 8.1.3, B
- R
- Referer header field 5.5, 5.5.2, 8.3.2, 9.4, B
- representation 3
- REST 3, 4.1, 11.2
- Retry-After header field 6.6.4, 7.1, 7.1.3, 8.3.2
- RFC1945 6.4, 11.2
- Section 9.3 6.4
- RFC2045 3.1.1.3, 11.1, A, A.1
- RFC2046 3.1.1.1, 3.1.1.4, 3.1.1.5, 11.1, A.2
- Section 4.5.1 3.1.1.5
- Section 5.1.1 3.1.1.4
- RFC2049 11.2, A.2
- Section 4 A.2
- RFC2068 5.1.1, 6.4, 11.2
- Section 10.3 6.4
- RFC2119 1.1, 11.1
- RFC2295 3.4, 11.2
- RFC2388 3.1.1.4, 11.2
- RFC2557 3.1.4.2, 11.2, A.6
- Section 4 3.1.4.2
- RFC2616 5.3.5, 11.2
- Section 14.4 5.3.5
- RFC2774 8.1.2, 11.2
- RFC2817 8.2, 11.2, B, B, B
- Section 7.1 8.2, B
- RFC2978 3.1.1.2, 11.2
- RFC3986 5.5.2, 7.1.2, 7.1.2, 11.1
- Section 4.2 7.1.2
- Section 5 7.1.2
- RFC4647 5.3.5, 5.3.5, 5.3.5, 5.3.5, 11.1
- Section 2.1 5.3.5
- Section 2.3 5.3.5
- Section 3 5.3.5
- Section 3.3.1 5.3.5
- RFC5226 8.1.1, 8.2.1, 8.4.1, 11.2
- Section 4.1 8.1.1, 8.2.1, 8.4.1
- RFC5234 1.2, 8.3.1, 11.1, C
- Appendix B.1 C
- RFC5246 4.3.6, 11.2
- RFC5322 5.5.1, 5.5.1, 7.1.1.1, 7.1.1.1, 7.1.1.1, 7.1.1.2, 11.2, A
- Section 3.3 7.1.1.1, 7.1.1.1
- Section 3.4 5.5.1, 5.5.1
- Section 3.6.1 7.1.1.2
- RFC5646 3.1.3.1, 3.1.3.1, 3.1.3.1, 11.1
- Section 2.1 3.1.3.1
- RFC5789 4.3.4, 11.2
- RFC5905 7.1.1.1, 11.2
- RFC5987 8.3.1, 11.2
- RFC5988 6.4.1, 11.2
- RFC6265 4.3.8, 5.4, 11.2
- RFC6266 11.2, B
- RFC6365 1.2, 3.1.1.2, 11.1
- RFC7230 1, 1.1, 1.2, 2, 2, 2, 3.1.2.1, 3.1.2.1, 3.1.2.1, 3.1.2.2, 3.1.4.1, 3.1.4.2, 3.3, 3.3, 3.3, 4.3.6, 4.3.7, 4.3.8, 4.3.8, 5.1, 5.1, 5.1.1, 5.5.3, 6.2.2, 6.3.4, 6.5.7, 6.5.10, 6.5.12, 6.5.15, 6.6.6, 7.4.2, 8.1.2, 8.3.1, 8.3.1, 8.3.1, 8.3.1, 8.3.1, 8.3.1, 8.3.1, 8.4, 8.4.1, 8.4.1, 9, 9.6, 10, 11.1, B, C, C, C, C, C, C, C, C, C, C, C, D
- Section 1.2 D
- Section 2.5 1.1
- Section 2.6 6.6.6
- Section 2.7 2, C, C, C
- Section 3.2 5.5.3, 7.4.2, 8.3.1, 8.3.1, C
- Section 3.2.3 C, C, C
- Section 3.2.4 8.3.1
- Section 3.2.6 8.3.1, C, C, C
- Section 3.3.1 3.1.2.2, 3.3
- Section 3.3 8.1.2
- Section 3.3.2 3.3, 6.5.10
- Section 4 8.4.1
- Section 4.1 8.3.1
- Section 4.2.1 3.1.2.1
- Section 4.2 8.4, 8.4.1
- Section 4.2.2 3.1.2.1
- Section 4.2.3 3.1.2.1
- Section 4.3 5.1
- Section 4.4 3.3
- Section 5.3 2, 4.3.6, 4.3.7, 6.5.12
- Section 5.4 5.1
- Section 5.5 2, 3.1.4.1, 3.1.4.2
- Section 5.7.1 4.3.8, 9.6
- Section 5.7.2 6.3.4
- Section 6.1 6.5.7, 8.3.1
- Section 6.6 5.1.1
- Section 6.7 6.2.2, 6.5.15
- Section 7 1.2, 8.3.1
- Section 8.3.1 4.3.8
- Section 9 9
- Section 10 10
- RFC7232 3, 4.1, 5.2, 5.2, 5.2, 5.2, 5.2, 5.2, 6.1, 6.1, 6.1, 7.2, 7.2, 7.2, 11.1
- Section 2.2 7.2
- Section 2.3 7.2
- Section 3.1 5.2
- Section 3.2 5.2
- Section 3.3 5.2
- Section 3.4 5.2
- Section 4 6.1
- Section 4.1 6.1
- Section 4.2 6.1
- Section 5 5.2
- RFC7233 3.1.1.4, 3.3, 4.3.1, 4.3.4, 5.1, 5.2, 6.1, 6.1, 6.1, 7.4, 8.1.2, 11.1, A.6
- Section 2.3 7.4
- Section 3.1 5.1
- Section 3.2 5.2
- Section 4 6.1
- Section 4.1 6.1
- Section 4.2 3.3, 4.3.4
- Section 4.4 6.1
- Appendix A A.6
- RFC7234 4.2.3, 4.3.1, 4.3.2, 4.3.2, 4.3.3, 4.3.4, 4.3.5, 5.1, 5.1, 6.1, 6.3.1, 6.3.4, 6.3.4, 6.3.5, 6.4.1, 6.4.2, 6.5.4, 6.5.5, 6.5.9, 6.5.12, 6.6.2, 7.1, 7.1, 7.1, 7.1, 7.1.4, 7.1.4, 8.2.2, 11.1
- Section 4.1 7.1.4
- Section 4.2.1 4.3.3
- Section 4.2.2 6.3.1, 6.3.4, 6.3.5, 6.4.1, 6.4.2, 6.5.4, 6.5.5, 6.5.9, 6.5.12, 6.6.2
- Section 4.3.5 4.3.2
- Section 4.4 4.3.4, 4.3.5
- Section 5.1 7.1
- Section 5.2 4.3.1, 4.3.2, 5.1, 7.1, 7.1.4
- Section 5.3 7.1
- Section 5.4 5.1
- Section 5.5 6.3.4, 7.1
- RFC7235 4.3.8, 5.4, 5.4, 5.4, 6.1, 6.1, 6.1, 7.1.4, 7.3, 7.3, 11.1
- Section 3 6.1
- Section 3.1 6.1
- Section 3.2 6.1
- Section 4.1 7.3
- Section 4.2 5.4, 7.1.4
- Section 4.3 7.3
- Section 4.4 5.4
- RFC7238 6.4.7, 11.2
- S
- safe 4.2.1
- selected representation 3, 7.2
- Server header field 7.4, 7.4.2, 8.3.2, 9.6
- Status Codes Classes
- 1xx Informational 6.2
- 2xx Successful 6.3
- 3xx Redirection 6.4, B
- 4xx Client Error 6.5
- 5xx Server Error 6.6
- T
- TRACE method 4.1, 4.3.8, 5.1.2, 8.1.3, B, B, B
- U
- User-Agent header field 5.5, 5.5.3, 7.4.2, 8.3.2, 9.6
- V
- Vary header field 3.4.1, 7.1, 7.1.4, 8.3.1, 8.3.2
- X
- x-compress (content coding) 3.1.2.1
- x-gzip (content coding) 3.1.2.1
Authors’ Addresses
Roy T. Fielding (editor)Adobe Systems Incorporated
345 Park Ave
San Jose, CA 95110
USA
Email: fielding@gbiv.com
URI: http://roy.gbiv.com/ Julian F. Reschke (editor)
greenbytes GmbH
Hafenweg 16
Muenster, NW 48155
Germany
Email: julian.reschke@greenbytes.de
URI: http://greenbytes.de/tech/webdav/
RFC 2616 Fielding, et al.
Each Status-Code is described below, including a description of which
method(s) it can follow and any metainformation required in the
response.
10.1 Informational 1xx
This class of status code indicates a provisional response,
consisting only of the Status-Line and optional headers, and is
terminated by an empty line. There are no required headers for this
class of status code. Since HTTP/1.0 did not define any 1xx status
codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client
except under experimental conditions.
A client MUST be prepared to accept one or more 1xx status responses
prior to a regular response, even if the client does not expect a 100
(Continue) status message. Unexpected 1xx status responses MAY be
ignored by a user agent.
Proxies MUST forward 1xx responses, unless the connection between the
proxy and its client has been closed, or unless the proxy itself
requested the generation of the 1xx response. (For example, if a
proxy adds a «Expect: 100-continue» field when it forwards a request,
then it need not forward the corresponding 100 (Continue)
response(s).)
10.1.1 100 Continue
The client SHOULD continue with its request. This interim response is
used to inform 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. See
section 8.2.3 for detailed discussion of the use and handling of this
status code.
10.1.2 101 Switching Protocols
The server understands and is willing to comply with the client’s
request, via the Upgrade message header field (section 14.42), for a
change in the application protocol being used on this connection. The
server will switch protocols to those defined by the response’s
Upgrade header field immediately after the empty line which
terminates the 101 response.
The protocol SHOULD be switched only when it is advantageous to do
so. For example, switching to a newer version of HTTP is advantageous
over older versions, and switching to a real-time, synchronous
protocol might be advantageous when delivering resources that use
such features.
10.2 Successful 2xx
This class of status code indicates that the client’s request was
successfully received, understood, and accepted.
10.2.1 200 OK
The request has succeeded. 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.
10.2.2 201 Created
The request has been fulfilled and resulted in a new resource being
created. 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 response
SHOULD include an entity containing a list of resource
characteristics and location(s) from which the user or user agent can
choose the one most appropriate. The entity format is specified by
the media type given in the Content-Type 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 202 (Accepted) response instead.
A 201 response MAY contain an ETag response header field indicating
the current value of the entity tag for the requested variant just
created, see section 14.19.
10.2.3 202 Accepted
The request has been accepted for processing, but the processing has
not been completed. The request might or might not eventually be
acted upon, as it might be disallowed when processing actually takes
place. There is no facility for re-sending a status code from an
asynchronous operation such as this.
The 202 response is intentionally non-committal. 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 or some estimate of when the
user can expect the request to be fulfilled.
10.2.4 203 Non-Authoritative Information
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. For example, including local
annotation information about the resource might result in a superset
of the metainformation known by the origin server. Use of this
response code is not required and is only appropriate when the
response would otherwise be 200 (OK).
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
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, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent’s active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
10.2.6 205 Reset Content
The server has fulfilled the request and the user agent SHOULD reset
the document view which caused the request to be sent. This response
is primarily intended to allow input for actions to take place via
user input, followed by a clearing of the form in which the input is
given so that the user can easily initiate another input action. The
response MUST NOT include an entity.
10.2.7 206 Partial Content
The server has fulfilled the partial GET request for the resource.
The request MUST have included a Range header field (section 14.35)
indicating the desired range, and MAY have included an If-Range
header field (section 14.27) to make the request conditional.
The response MUST include the following header fields:
- Either a Content-Range header field (section 14.16) indicating the range included with this response, or a multipart/byteranges Content-Type including Content-Range fields for each part. If a Content-Length header field is present in the response, its value MUST match the actual number of OCTETs transmitted in the message-body.
- Date
- ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request
- Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant
If the 206 response is the result of an If-Range request that used a
strong cache validator (see section 13.3.3), the response SHOULD NOT
include other entity-headers. If the response is the result of an
If-Range request that used a weak validator, the response MUST NOT
include other entity-headers; this prevents inconsistencies between
cached entity-bodies and updated headers. Otherwise, the response
MUST include all of the entity-headers that would have been returned
with a 200 (OK) response to the same request.
A cache MUST NOT combine a 206 response with other previously cached
content if the ETag or Last-Modified headers do not match exactly,
see 13.5.4.
A cache that does not support the Range and Content-Range headers
MUST NOT cache 206 (Partial) responses.
10.3 Redirection 3xx
This class of status code indicates that further action needs to be
taken by the user agent in order to fulfill the request. The action
required MAY be carried out by the user agent without interaction
with the user if and only if the method used in the second request is
GET or HEAD. A client SHOULD detect infinite redirection loops, since
such loops generate network traffic for each redirection.
Note: previous versions of this specification recommended a maximum of five redirections. Content developers should be aware that there might be clients that implement such a fixed limitation.
10.3.1 300 Multiple Choices
The requested resource corresponds to any one of a set of
representations, each with its own specific location, and agent-
driven negotiation information (section 12) is being provided so that
the user (or user agent) can select a preferred representation and
redirect its request to that location.
Unless it was a HEAD request, the response SHOULD include an entity
containing a list of resource characteristics and location(s) from
which the user or user agent can choose the one most appropriate. The
entity format is specified by the media type given in the Content-
Type header field. Depending upon the format and the capabilities of
the user agent, selection of the most appropriate choice MAY be
performed automatically. However, this specification does not define
any standard for such automatic selection.
If the server has a preferred choice of representation, it SHOULD
include the specific URI for that representation in the Location
field; user agents MAY use the Location field value for automatic
redirection. This response is cacheable unless indicated otherwise.
10.3.2 301 Moved Permanently
The requested resource has been assigned a new permanent URI and any
future references to this resource SHOULD use one of the returned
URIs. Clients with link editing capabilities ought to automatically
re-link references to the Request-URI to one or more of the new
references returned by the server, where possible. This response is
cacheable unless indicated otherwise.
The new permanent 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 301 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.
Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.
10.3.3 302 Found
The requested resource resides temporarily under a different URI.
Since the redirection might be altered on occasion, the client SHOULD
continue to use the Request-URI for future requests. This response
is only cacheable if indicated by a Cache-Control or Expires header
field.
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 302 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.
Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. 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.
10.3.4 303 See Other
The response to the request can be found under a different URI and
SHOULD be retrieved using a GET method on that resource. This method
exists primarily to allow the output of a POST-activated script to
redirect the user agent to a selected resource. The new URI is not a
substitute reference for the originally requested resource. The 303
response MUST NOT be cached, but the response to the second
(redirected) request might be cacheable.
The different 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).
Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.
10.3.5 304 Not Modified
If the client has performed a conditional GET request and access is
allowed, but the document has not been modified, the server SHOULD
respond with this status code. The 304 response MUST NOT contain a
message-body, and thus is always terminated by the first empty line
after the header fields.
The response MUST include the following header fields:
- Date, unless its omission is required by section 14.18.1
If a clockless origin server obeys these rules, and proxies and
clients add their own Date to any response received without one (as
already specified by [RFC 2068], section 14.19), caches will operate
correctly.
- ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request
- Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant
If the conditional GET used a strong cache validator (see section
13.3.3), the response SHOULD NOT include other entity-headers.
Otherwise (i.e., the conditional GET used a weak validator), the
response MUST NOT include other entity-headers; this prevents
inconsistencies between cached entity-bodies and updated headers.
If a 304 response indicates an entity not currently cached, then the
cache MUST disregard the response and repeat the request without the
conditional.
If a cache uses a received 304 response to update a cache entry, the
cache MUST update the entry to reflect any new field values given in
the response.
10.3.6 305 Use Proxy
The requested resource MUST be accessed through the proxy given by
the Location field. The Location field gives the URI of the proxy.
The recipient is expected to repeat this single request via the
proxy. 305 responses MUST only be generated by origin servers.
Note: RFC 2068 was not clear that 305 was intended to redirect a single request, and to be generated by origin servers only. Not observing these limitations has significant security consequences.
10.3.7 306 (Unused)
The 306 status code was used in a previous version of the
specification, is no longer used, and the code is reserved.
10.3.8 307 Temporary Redirect
The requested resource resides temporarily under a different URI.
Since the redirection MAY be altered on occasion, the client SHOULD
continue to use the Request-URI for future requests. This response
is only cacheable if indicated by a Cache-Control or Expires header
field.
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) , since many pre-HTTP/1.1 user agents do not
understand the 307 status. Therefore, the note SHOULD contain the
information necessary for a user to repeat the original request on
the new URI.
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.
10.4 Client Error 4xx
The 4xx class of status code is intended for cases in which the
client seems to have erred. Except when responding to a HEAD request,
the server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent
condition. These status codes are applicable to any request method.
User agents SHOULD display any included entity to the user.
If the client is sending data, a server implementation using TCP
SHOULD be careful to ensure that the client acknowledges receipt of
the packet(s) containing the response, before the server closes the
input connection. If the client continues sending data to the server
after the close, the server’s TCP stack will send a reset packet to
the client, which may erase the client’s unacknowledged input buffers
before they can be read and interpreted by the HTTP application.
10.4.1 400 Bad Request
The request could not be understood by the server due to malformed
syntax. The client SHOULD NOT repeat the request without
modifications.
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a
WWW-Authenticate header field (section 14.47) containing a challenge
applicable to the requested resource. The client MAY repeat the
request with a suitable Authorization header field (section 14.8). 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. HTTP access authentication
is explained in «HTTP Authentication: Basic and Digest Access
Authentication» [43].
10.4.3 402 Payment Required
This code is reserved for future use.
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the
reason for the refusal in the entity. If the server does not wish to
make this information available to the client, the status code 404
(Not Found) can be used instead.
10.4.5 404 Not Found
The server has not found anything matching the Request-URI. 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.
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the
resource identified by the Request-URI. The response MUST include an
Allow header containing a list of valid methods for the requested
resource.
10.4.7 406 Not Acceptable
The resource identified by the request is only capable of generating
response entities which have content characteristics not acceptable
according to the accept headers sent in the request.
Unless it was a HEAD request, the response SHOULD include an entity
containing a list of available entity characteristics and location(s)
from which the user or user agent can choose the one most
appropriate. The entity format is specified by the media type given
in the Content-Type header field. Depending upon the format and the
capabilities of the user agent, selection of the most appropriate
choice MAY be performed automatically. However, this specification
does not define any standard for such automatic selection.
Note: HTTP/1.1 servers are allowed to return responses which are not acceptable according to the accept headers sent in the request. In some cases, this may even be preferable to sending a 406 response. User agents are encouraged to inspect the headers of an incoming response to determine if it is acceptable.
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.
10.4.8 407 Proxy Authentication Required
This code is similar to 401 (Unauthorized), but indicates that the
client must first authenticate itself with the proxy. The proxy MUST
return a Proxy-Authenticate header field (section 14.33) containing a
challenge applicable to the proxy for the requested resource. The
client MAY repeat the request with a suitable Proxy-Authorization
header field (section 14.34). HTTP access authentication is explained
in «HTTP Authentication: Basic and Digest Access Authentication»
[43].
10.4.9 408 Request Timeout
The client did not produce a request within the time that the server
was prepared to wait. The client MAY repeat the request without
modifications at any later time.
10.4.10 409 Conflict
The request could not be completed due to a conflict with the current
state of the resource. This code is only allowed in situations where
it is expected that the user might be able to resolve the conflict
and resubmit the request. The response body SHOULD include enough
information for the user to recognize the source of the conflict.
Ideally, the response entity would include enough information for the
user or user agent to fix the problem; however, that might not be
possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For
example, if versioning were being used and the entity being PUT
included changes to a resource which conflict with those made by an
earlier (third-party) request, the server might use the 409 response
to indicate that it can’t complete the request. In this case, the
response entity would likely contain a list of the differences
between the two versions in a format defined by the response
Content-Type.
10.4.11 410 Gone
The requested resource is no longer available at the server and no
forwarding address is known. This condition is expected to be
considered permanent. Clients with link editing capabilities SHOULD
delete references to the Request-URI after user approval. If the
server does not know, or has no facility to determine, whether or not
the condition is permanent, the status code 404 (Not Found) SHOULD be
used instead. This response is cacheable unless indicated otherwise.
The 410 response is primarily intended to assist the task of web
maintenance by notifying the recipient that the resource is
intentionally unavailable and that the server owners desire that
remote links to that resource be removed. Such an event is common for
limited-time, promotional services and for resources belonging to
individuals no longer working at the server’s site. It is not
necessary to mark all permanently unavailable resources as «gone» or
to keep the mark for any length of time — that is left to the
discretion of the server owner.
10.4.12 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 containing the length of the message-body
in the request message.
10.4.13 412 Precondition Failed
The precondition given in one or more of the request-header fields
evaluated to false when it was tested on the server. This response
code allows the client to place preconditions on the current resource
metainformation (header field data) and thus prevent the requested
method from being applied to a resource other than the one intended.
10.4.14 413 Request Entity Too Large
The server is refusing to process a request because the request
entity is larger than the server is willing or able to process. The
server MAY close the connection to prevent the client from continuing
the request.
If the condition is temporary, the server SHOULD include a Retry-
After header field to indicate that it is temporary and after what
time the client MAY try again.
10.4.15 414 Request-URI Too Long
The server is refusing to service the request because the Request-URI
is longer than the server is willing to interpret. This rare
condition is only likely to occur when a client has improperly
converted a POST request to a GET request with long query
information, when the client has descended into a URI «black hole» of
redirection (e.g., a redirected URI prefix that points to a suffix of
itself), or when the server is under attack by a client attempting to
exploit security holes present in some servers using fixed-length
buffers for reading or manipulating the Request-URI.
10.4.16 415 Unsupported Media Type
The server is refusing to service the request because the entity of
the request is in a format not supported by the requested resource
for the requested method.
10.4.17 416 Requested Range Not Satisfiable
A server SHOULD return a response with this status code if a request
included a Range request-header field (section 14.35), and none of
the range-specifier values in this field overlap the current extent
of the selected resource, and the request did not include an If-Range
request-header field. (For byte-ranges, this means that the first-
byte-pos of all of the byte-range-spec values were greater than the
current length of the selected resource.)
When this status code is returned for a byte-range request, the
response SHOULD include a Content-Range entity-header field
specifying the current length of the selected resource (see section
14.16). This response MUST NOT use the multipart/byteranges content-
type.
10.4.18 417 Expectation Failed
The expectation given in an Expect request-header field (see section
14.20) could not be met by this server, or, if the server is a proxy,
the server has unambiguous evidence that the request could not be met
by the next-hop server.
10.5 Server Error 5xx
Response status codes beginning with the digit «5» indicate cases in
which the server is aware that it has erred or is incapable of
performing the request. Except when responding to a HEAD request, the
server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent
condition. User agents SHOULD display any included entity to the
user. These response codes are applicable to any request method.
10.5.1 500 Internal Server Error
The server encountered an unexpected condition which prevented it
from fulfilling the request.
10.5.2 501 Not Implemented
The server does not support the functionality required to fulfill the
request. This is the appropriate response when the server does not
recognize the request method and is not capable of supporting it for
any resource.
10.5.3 502 Bad Gateway
The server, while acting as a gateway or proxy, received an invalid
response from the upstream server it accessed in attempting to
fulfill the request.
10.5.4 503 Service Unavailable
The server is currently unable to handle the request due to a
temporary overloading or maintenance of the server. The implication
is that this is a temporary condition which will be alleviated after
some delay. If known, the length of the delay MAY be indicated in a
Retry-After header. If no Retry-After is given, the client SHOULD
handle the response as it would for a 500 response.
Note: The existence of the 503 status code does not imply that a server must use it when becoming overloaded. Some servers may wish to simply refuse the connection.
10.5.5 504 Gateway Timeout
The server, while acting as a gateway or proxy, did not receive a
timely response from the upstream server specified by the URI (e.g.
HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed
to access in attempting to complete the request.
Note: Note to implementors: some deployed proxies are known to return 400 or 500 when DNS lookups time out.
10.5.6 505 HTTP Version Not Supported
The server does not support, or refuses to support, the HTTP protocol
version that was used in the request message. The server is
indicating that it is unable or unwilling to complete the request
using the same major version as the client, as described in section
3.1, other than with this error message. The response SHOULD contain
an entity describing why that version is not supported and what other
protocols are supported by that server.