Which standard HTTP header tells a server which media type is expected by the client?
Show
Chapter 4. Metadata DesignHTTP HeadersVarious forms of metadata may be conveyed through the entity headers contained within HTTP’s request and response messages. HTTP defines a set of standard headers, some of which provide information about a requested resource. Other headers indicate something about the representation carried by the message. Finally, a few headers serve as directives to control intermediary caches. This brief chapter suggests a set of rules to help REST API designers work with HTTP’s standard headers. Rule: Content-Type must be usedThe Rule: Content-Length should be usedThe Rule: Last-Modified should be used in responsesThe Rule: ETag should be used in responsesThe value of Clients may choose to save an WarningGenerating an Rule: Stores must support conditional PUT requestsA store resource uses the The following example illustrates how a REST API can support conditional Two client programs, client#1 and client#2, use a REST API’s /objects store resource to share some information between them. Client#1 sends a Some time later, client#2 decides to share some data and it requests the
exact same storage URI (/objects/2113). Now the REST API is able to map this URI to an existing resource, which makes it unclear about the client request’s intent. The REST API has not been given enough information to decide whether or not it should overwrite client#1’s stored resource state with the new data from client#2. In this scenario, the API is forced to return a If client#2 decides to update the stored data, it may retry its request to include the NoteHTTP supports conditional requests with the Rule: Location must be used to specify the URI of a newly created resourceThe In a Rule: Cache-Control, Expires, and Date response headers should be used to encourage cachingCaching is one of the most useful features built on top of HTTP. You can take advantage of caching to reduce client-perceived latency, to increase reliability, and to reduce the load on an API’s servers. Caches can be anywhere. They can be in the API’s server network, content delivery networks (CDNs), or the client’s network. When serving a representation, include a Cache-Control: max-age=60, must-revalidate To support legacy HTTP
1.0 caches, a REST API should include an Date: Tue, 15 Nov 1994 08:12:31 GMT Expires: Thu, 01 Dec 1994 16:00:00 GMT Rule: Cache-Control, Expires, and Pragma response headers may be used to discourage cachingIf a REST API’s response must not cached, add Rule: Caching should be encouragedThe Rule: Expiration caching headers should be used with 200 (“OK”) responsesSet expiration caching headers in responses to successful Rule: Expiration caching headers may optionally be used with 3xx and 4xx responsesIn addition to successful responses with the Rule: Custom HTTP headers must not be used to change the behavior of HTTP methodsYou can optionally use custom headers for informational purposes only. Implement clients and servers such that they do not fail when they do not find expected custom headers. If the information you are conveying through a custom HTTP header is important for the correct interpretation of the request or response, include that information in the body of the request or response or the URI used for the request. Avoid custom headers for such usages. To identify the form of the data contained within a request or response message body, the Media Type SyntaxMedia types have the following syntax: type "/" subtype *( ";" parameter ) The type value may be one of: Note that parameters may follow the type/subtype in the form of The two examples below demonstrate a Content-type: text/html; charset=ISO-8859-4 Content-type: text/plain; charset="us-ascii" Registered Media TypesThe Internet Assigned Numbers Authority[26] (IANA) governs the set of registered media types and provides links to each type’s published specification (RFC). The IANA allows anyone to propose a new media type by filling out the “Application for Media Type” form found at http://www.iana.org/cgi-bin/mediatypes.pl. Some commonly used registered media types are listed below: text/plain A plain text format with no specific content structure or markup.[27] text/htmlContent that is formatted using the HyperText Markup Language (HTML).[28] image/jpegAn image compression method that was standardized by the Joint Photographic Experts Group (JPEG).[29] application/xmlContent that is structured using the Extensible Markup Language (XML).[30] application/atom+xmlContent that uses the Atom Syndication Format (Atom), which is an XML-based format that structures data into lists known as feeds.[31] application/javascriptSource code written in the JavaScript programming language.[32] application/jsonThe JavaScript Object Notation (JSON) text-based format that is often used by programs to exchange structured data.[33] Vendor-Specific Media TypesMedia types use the subtype prefix “vnd” to indicate that they are owned or controlled by a “vendor.” Vendor-specific media types convey a clear description of a message’s content to the programs that understand their meaning. Unlike their more common counterparts, vendor-specific media types impart application-specific metadata that makes a message more meaningful to the web component that receives it. Vendor-specific media types may also be registered with the IANA. For example, the following vendor-specific types are among the many listed in the IANA’s registry (http://www.iana.org/assignments/media-types): application/vnd.ms-excel application/vnd.lotus-notes text/vnd.sun.j2me.app-descriptor Client developers are encouraged to rely on the self-descriptive features of a REST API. In other words, client programs should hardcode as few API-specific details as possible. This goal influences many aspects of a REST API’s design, including opaque URIs, hypermedia-based actions with resource state awareness, and descriptive media types. Rule: Application-specific media types should be usedREST APIs treat the body of an HTTP request or response as part of an application-specific interaction. While the body may be formatted using languages such as JSON or XML, it usually has semantics that require special processing beyond simply parsing the language’s syntax. As an example, consider a REST API URI such as http://api.soccer.restapi.org/players/2113 that responds to Alternatively, the response’s # NOTE: the line breaks below are for the sake of visual clarity. application/wrml; format="http://api.formats.wrml.org/application/json"; schema="http://api.schemas.wrml.org/soccer/Player" The WRML media type.[34] The required format parameter’s value identifies a document resource that describes the JSON format itself. The required schema parameter’s value identifies a separate document that details the This media type may appear excessive when compared to simpler ones like application/json. However, this is a worthwhile trade-off since this media type communicates—directly to clients—distinct and complementary bits of information regarding the content of a message. The application/wrml media type’s self-descriptive and pluggable design reduces the need for information to be communicated out-of-band and then hardcoded by client developers. Media Type Format DesignMost media types identify a format using a simple string, like application/json. Instead, by using a More importantly, by leveraging REST’s code-on-demand constraint, the format document’s representation can provide links to formatting and parsing code, which clients can download and execute to serialize and deserialize an HTTP message body’s content. By providing this code, available for various programming languages and runtime environments, an API can programmatically teach its clients how to interoperate with its representation formats. The future-proof nature of this design may prove especially useful when a REST API wishes to adopt a new format that is not yet widely supported by its clients. The section Rule: A consistent form should be used to represent media type formats, outlines the structure of a format document’s representation. Media Type Schema DesignAs discussed next in Chapter 5, a resource’s state representation consists of fields and links. For a given “class” of resource, the set of expected fields and context-sensitive links can be described by a schema document. The WRML media type’s schema parameter references a cacheable schema document, which describes a resource type’s fields and links; independent of any specific representational format. This separation of concerns allows multiple representation formats to be negotiated by clients and supported by REST APIs with relative ease. With a set of standard primitive types, outlined in Field Representation, a schema document can describe a resource representation’s fields in a format-independent manner. The section Rule: A consistent form should be used to represent media type schemas, details the structure of a schema document’s representation. Media Type Schema VersioningThe different versions of a given schema should be organized as different schema documents, with distinct URIs. This design is borrowed from the approach traditionally used by the W3C[35] and
IETF[36] for versioning the URIs of Internet Drafts on their way to becoming approved standards. The example below shows the URI of a schema document that details the fields and links of a soccer http://api.schemas.wrml.org/soccer/Player-2 The http://api.schemas.wrml.org/soccer/Player The URI of a resource type’s current schema version always identifies the concept of the most recent version. A schema document URI that ends with a number permanently identifies a specific version of the schema. Therefore the latest version of a schema is always modeled by two separate resources which conceptually overlap while the numbered version is also the current one. This overlap results in the two distinct resources, with two separate URIs, consistently having the same state representation. Rule: Media type negotiation should be supported when multiple representations are availableAllow clients to negotiate for a given format and schema by submitting an # NOTE: the line breaks below are for the sake of visual clarity. Accept: application/wrml; format="http://api.formats.wrml.org/text/html"; schema="http://api.schemas.wrml.org/soccer/Team" Using media type negotiation clients can select a format. Using media type negotiation clients can select the schema version that will work best for them. Additionally, to facilitate browser-based viewing and debugging of a REST API’s responses, consider supporting raw media types as shown in the example below: Accept: application/json This will allow web browser add-ons such as JSONView to render a REST API’s responses as JSON. Rule: Media type selection using a query parameter may be supportedTo enable simple links and easy debugging, REST APIs may support media type selection via a query parameter named accept with a value format that mirrors that of the GET /bookmarks/mikemassedotcom?accept=application/xml This is a more precise and generic approach to media type identification that should be preferred over the common alternative of appending a virtual file extension like .xml to the URI’s path. The virtual file extension approach binds the resource and its representation together, implying that they are one and the same. WarningMedia type selection (or negotiation) via a query parameter is a form of tunneling that conveys metadata in the URI rather than in HTTP’s intended slot: the Recap
This chapter covered the design rules for a REST API’s metadata conveyed through HTTP headers and media types. Table 4-1 summarizes the vocabulary terms that were used in this chapter. Table 4-1. Vocabulary review
Table 4-2 recaps a REST API’s use of the HTTP headers. Table 4-2. HTTP response header summary
What HTTP request header is used to identify the acceptable content types that can be returned?The Accept request-header field can be used to specify certain media types which are acceptable for the response.
What is ContentThe Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc. In response, it tells about the type of returned content, to the client.
Which header is used to tell server what is the format of data being sent in the request?The Accept header is used to inform the server by the client that which content type is understandable by the client expressed as MIME-types. It is a request type header. This header is used to indicate what character set are acceptable for the response from the server.
Which HTTP request header is used to identify the URI of the resource from which a request URI was obtained?Referer: This optional header field allows the client to specify, for the server's benefit, the address ( URI ) of the document (or element within the document) from which the URI in the request was obtained.
|