Movatterモバイル変換


[0]ホーム

URL:


Latest Specification (v1.1)

Status

This page presents the latest published version of JSON:API, which is currently version 1.1. New versions of JSON:APIwill always be backwards compatible using anever remove, only add strategy. Additions can be proposed in ourdiscussion forum.

If you catch an error in the specification’s text, or if you write an implementation, please let us know by opening an issue or pull request at ourGitHub repository.

Introduction

JSON:API is a specification for how a client should request that resources befetched or modified, and how a server should respond to those requests. JSON:APIcan be easily extended withextensions andprofiles.

JSON:API is designed to minimize both the number of requests and the amount ofdata transmitted between clients and servers. This efficiency is achievedwithout compromising readability, flexibility, or discoverability.

JSON:API requires use of the JSON:API media type(application/vnd.api+json)for exchanging data.

Semantics

All document members, query parameters, and processing rules defined bythis specification are collectively called “specification semantics”.

Certain document members, query parameters, and processing rules are reservedfor implementors to define at their discretion. These are called “implementationsemantics”.

All other semantics are reserved for potential future use by this specification.

Conventions

The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”,“SHOULD NOT”, “RECOMMENDED”, “NOT RECOMMENDED”, “MAY”, and “OPTIONAL” in thisdocument are to be interpreted as described inBCP 14[RFC2119][RFC8174]when, and only when, they appear in all capitals, as shown here.

The JSON:API Media Type

The JSON:API media type isapplication/vnd.api+json.

Media Type Parameters

The JSON:API specification supports two media type parameters:ext andprofile, which are used to specifyextensions andprofiles, respectively.

Note: A media type parameter is an extra piece of information that canaccompany a media type. For example, in the headerContent-Type: text/html;charset="utf-8", the media type istext/html andcharset is a parameter.

Extensions

Extensions provide a means to “extend” the base specification by definingadditionalspecification semantics.

Extensions cannot alter or remove specification semantics, nor can they specifyimplementation semantics.

Profiles

Profiles provide a means to share a particular usage of the specification amongimplementations.

Profiles can specifyimplementation semantics, but cannot alter,add to, or remove specification semantics.

Rules for Media Type Parameters

The JSON:API media typeMUST NOT be specified with any media type parametersother thanext andprofile. Theext parameter is used to supportextensions and theprofile parameter is used to supportprofiles.

Extensions and profiles are each uniquely identified by aURI. Visiting an extension’s or aprofile’s URISHOULD return documentation that describes its usage. Thevalues of theext andprofile parametersMUST equal a space-separated(U+0020 SPACE, “ “) list of extension or profile URIs, respectively.

Note: When serializing theext orprofile media type parameters, the HTTPspecification requires that parameter values be surrounded by quotation marks(U+0022 QUOTATION MARK, “"”).

Rules for Extensions

An extensionMAY impose additional processing rules or further restrictionsand itMAY define new object members as described below.

An extensionMUST NOT lessen or remove any processing rules, restrictions orobject member requirements defined in this specification or other extensions.

An extensionMAY define new members within the document structure defined bythis specification. The rules for extension member names are coveredbelow.

An extensionMAY define new query parameters. The rules for extension-definedquery parameters are coveredbelow.

When an extension defines new query parameters or document members, theextensionMUST define a namespace to guarantee that extensions will neverconflict with current or future versions of this specification. A namespaceMUST meet all of the following conditions:

  • A namespaceMUST contain at least one character.
  • A namespaceMUST contain only these characters:
    • U+0061 to U+007A, “a-z”
    • U+0041 to U+005A, “A-Z”
    • U+0030 to U+0039, “0-9”

An extensionMUST NOT define more than one namespace. The namespace used forall query parameters and document membersMUST be the same for any givenextension.

In the following example, an extension with the namespaceversion hasspecified a resource object memberversion:id to support per-resourceversioning. This member might appear as follows:

HTTP/1.1200OKContent-Type:application/vnd.api+json;ext="https://jsonapi.org/ext/version"//...{"type":"articles","id":"1","version:id":"42","attributes":{"title":"Rails is Omakase"}}//...

Rules for Profiles

The rules for profile usage are dictated byRFC6906.

A profileMAY define document members and processing rules that are reservedfor implementors.

A profileMUST NOT define any query parameters exceptimplementation-specific query parameters.

A profileMUST NOT alter or remove processing rules that have been definedby this specification or by anextension. However, a profileMAY define processing rules for query parameters whose processing ruleshave been reserved for implementors to define at their discretion.

For example, a profile could define rules for interpretingthefilter queryparameter, but it could not specify that relationshipnames intheinclude query parameter arespace-separated instead of dot-separated.

Unlike extensions, profiles do not need to define a namespace for documentmembers because profiles cannot define specification semantics and thus cannotconflict with current or future versions of this specification. However, it ispossible for profiles to conflict with other profiles. Therefore, it is theresponsibility of implementors to ensure that they do not support conflictingprofiles.

In the following example, a profile has defined atimestampsattribute. According to the profile, the attribute must be anobject containing acreated member and amodified member and these members’values must use theRFC 3339 format.With such a profile applied, a response might appear as follows:

HTTP/1.1200OKContent-Type:application/vnd.api+json;profile="https://example.com/resource-timestamps"//...{"type":"articles","id":"1","attributes":{"title":"Rails is Omakase","timestamps":{"created":"2020-07-21T12:09:00Z","modified":"2020-07-30T10:19:01Z"}}}//...

Content Negotiation

Universal Responsibilities

Clients and serversMUST send all JSON:API payloads using the JSON:API mediatype in theContent-Type header.

Clients and serversMUST specify theext media type parameter in theContent-Type header when they have applied one or more extensions to aJSON:API document.

Clients and serversMUST specify theprofile media type parameters in theContent-Type header when they have applied one or more profiles to a JSON:APIdocument.

Client Responsibilities

When processing a JSON:API response document, clientsMUST ignore anyparameters other thanext andprofile parameters in the server’sContent-Type header.

A clientMAY use theext media type parameter in anAccept header torequire that a server apply all the specified extensions to the responsedocument.

A clientMAY use theprofile media type parameter in anAccept headerto request that the server apply one or more profiles to the response document.

Note: A client is allowed to send more than one acceptable media type in theAccept header, including multiple instances of the JSON:API media type. Thisallows clients to request different combinations of theext andprofilemedia type parameters. A client can usequality valuesto indicate that some combinations are less preferable than others. Media typesspecified without a qvalue are equally preferable to each other, regardless oftheir order, and are always considered more preferable than a media type with aqvalue less than 1.

Server Responsibilities

If a request specifies theContent-Type header with the JSON:API media type,serversMUST respond with a415 Unsupported Media Type status code ifthat media type contains any media type parameters other thanext orprofile.

If a request specifies theContent-Type header with an instance ofthe JSON:API media type modified by theext media type parameter and thatparameter contains an unsupported extension URI, the serverMUST respondwith a415 Unsupported Media Type status code.

Note: JSON:API servers that do not support version 1.1 of this specification will respond with a415 Unsupported Media Type client error if theext orprofile media type parameter is present.

If a request’sAccept header contains an instance of the JSON:API media type,serversMUST ignore instances of that media type which are modified by amedia type parameter other thanext orprofile. If all instances of thatmedia type are modified with a media type parameter other thanext orprofile,serversMUST respond with a406 Not Acceptable status code. If everyinstance of that media type is modified by theext parameter and each containsat least one unsupported extension URI, the serverMUST also respond with a406 Not Acceptable.

If theprofile parameter is received, a serverSHOULD attempt to apply anyrequested profile(s) to its response. A serverMUST ignore any profilesthat it does not recognize.

Note: The above rules guarantee strict agreement on extensions between the client and server, while the application of profiles is left to the discretion of the server.

Servers that support theext orprofile media type parametersSHOULDspecify theVary header withAccept as one of its values. This applies toresponses with and without anyprofiles orextensions applied.

Note: Some HTTP intermediaries (e.g. CDNs) may ignore theVary headerunless specifically configured to respect it.

Document Structure

This section describes the structure of a JSON:API document, which is identifiedby theJSON:API media type. JSON:API documents aredefined in JavaScript Object Notation (JSON) [RFC8259].

Although the same media type is used for both request and response documents,certain aspects are only applicable to one or the other. These differences arecalled out below.

ExtensionsMAY define new members within the document structure. ThesemembersMUST comply with the naming requirements specifiedbelow.

Unless otherwise noted, objects defined by this specification or any appliedextensionsMUST NOT contain any additional members. Client and serverimplementationsMUST ignore non-compliant members.

Note: These conditions allow this specification to evolve through additivechanges.

Top Level

A JSON objectMUST be at the root of every JSON:API request and responsedocument containing data. This object defines a document’s “top level”.

A documentMUST contain at least one of the following top-level members:

  • data: the document’s “primary data”.
  • errors: an array oferror objects.
  • meta: ameta object that contains non-standardmeta-information.
  • a member defined by an appliedextension.

The membersdata anderrorsMUST NOT coexist in the same document.

A documentMAY contain any of these top-level members:

  • jsonapi: an object describing the server’s implementation.
  • links: alinks object related to the document as a whole.
  • included: an array ofresource objects that are related to the primarydata and/or each other (“included resources”).

If a document does not contain a top-leveldata key, theincluded memberMUST NOT be present either.

The top-levellinks objectMAY contain the following members:

  • self: thelink that generated the current response document. If adocument has extensions or profiles applied to it, this linkSHOULD berepresented by alink object with thetype target attribute specifying theJSON:API media type with all applicable parameters.
  • related: arelated resource link when the primary data represents aresource relationship.
  • describedby: alink to a description document (e.g. OpenAPI or JSONSchema) for the current document.
  • pagination links for the primary data.

Note: Theself link in the top-levellinks object allows a client torefresh the data represented by the current response document. The clientshould be able to use the provided link without applying any additionalinformation. Therefore the link must contain the query parameters providedby the client to generate the response document. This includes but is notlimited to query parameters used forinclusion of related resources,sparse fieldsets,sorting,pagination andfiltering.

The document’s “primary data” is a representation of the resource or collectionof resources targeted by a request.

Primary dataMUST be either:

For example, the following primary data is a single resource object:

{"data":{"type":"articles","id":"1","attributes":{//...thisarticle'sattributes},"relationships":{//...thisarticle'srelationships}}}

The following primary data is a singleresource identifier object thatreferences the same resource:

{"data":{"type":"articles","id":"1"}}

A logical collection of resourcesMUST be represented as an array, even ifit only contains one item or is empty.

Resource Objects

“Resource objects” appear in a JSON:API document to represent resources.

A resource objectMUST contain at least the following top-level members:

  • id
  • type

Exception: Theid member is not required when the resource object originatesat the client and represents a new resource to be created on the server. In thatcase, a clientMAY include alid member to uniquely identify the resourcebytypelocally within the document.

In addition, a resource objectMAY contain any of these top-level members:

  • attributes: anattributes object representing some of the resource’s data.
  • relationships: arelationships object describing relationships between the resource and other JSON:API resources.
  • links: alinks object containing links related to the resource.
  • meta: ameta object containing non-standard meta-information about aresource that can not be represented as an attribute or relationship.

Here’s how an article (i.e. a resource of type “articles”) might appear in a document:

//...{"type":"articles","id":"1","attributes":{"title":"Rails is Omakase"},"relationships":{"author":{"links":{"self":"/articles/1/relationships/author","related":"/articles/1/author"},"data":{"type":"people","id":"9"}}}}//...

Identification

As noted above, everyresource objectMUST contain atype member. Every resource objectMUST also contain anid member,except when the resource object originates at the client and represents a newresource to be created on the server. Ifid is omitted due to this exception,alid memberMAY be included to uniquely identify the resource bytypelocally within the document. The value of thelid memberMUST beidentical for every representation of the resource in the document, includingresource identifier objects.

The values of theid,type, andlid membersMUST be strings.

Within a given API, each resource object’stype andid pairMUSTidentify a single, unique resource. (The set of URIs controlled by a server,or multiple servers acting as one, constitute an API.)

Thetype member is used to describeresource objects that share commonattributes and relationships.

The values oftype membersMUST adhere to the same constraints asmember names.

Note: This spec is agnostic about inflection rules, so the value oftypecan be either plural or singular. However, the same value should be usedconsistently throughout an implementation.

Fields

A resource object’sattributes and itsrelationships are collectively calledits “fields”.

Fields for aresource objectMUST share a common namespace with eachother and withtype andid. In other words, a resource can not have anattribute and relationship with the same name, nor can it have an attributeor relationship namedtype orid.

Attributes

The value of theattributes keyMUST be an object (an “attributesobject”). Members of the attributes object (“attributes”) represent informationabout theresource object in which it’s defined.

Attributes may contain any valid JSON value, including complex data structuresinvolving JSON objects and arrays.

Keys that reference related resources (e.g.author_id)SHOULD NOT appearas attributes. Instead,relationshipsSHOULD be used.

Note: Seefields andmember names for more restrictions on this container.

Relationships

The value of therelationships keyMUST be an object (a “relationshipsobject”). Each member of a relationships object representsa “relationship” from theresource objectin which it has been defined to other resource objects.

Relationships may be to-one or to-many.

A relationship’s name is given by its key. The value at that keyMUST be anobject (“relationship object”).

A “relationship object”MUST contain at least one of the following:

  • links: alinks object containing at least one of the following:
    • self: a link for the relationship itself (a “relationship link”). Thislink allows the client to directly manipulate the relationship. For example,removing anauthor through anarticle’s relationship URL would disconnectthe person from thearticle without deleting thepeople resource itself.When fetched successfully, this link returns thelinkagefor the related resources as its primary data.(SeeFetching Relationships.)
    • related: arelated resource link
    • a member defined by an appliedextension.
  • data:resource linkage
  • meta: ameta object that contains non-standard meta-information about therelationship.
  • a member defined by an appliedextension.

A relationship object that represents a to-many relationshipMAY also containpagination links under thelinks member, as described below. Anypagination links in a relationship objectMUST paginate the relationshipdata, not the related resources.

Note: Seefields andmember names for more restrictions on this container.

Related Resource Links

A “related resource link” provides access toresource objectslinkedin arelationship. When fetched, the related resource object(s)are returned as the response’s primary data.

For example, anarticle’scommentsrelationship couldspecify alink that returns a collection of commentresource objectswhen retrieved through aGET request.

If present, a related resource linkMUST reference a valid URL, even if therelationship isn’t currently associated with any target resources. Additionally,a related resource linkMUST NOT change because its relationship’s contentchanges.

Resource Linkage

Resource linkage in acompound document allows a client to link together allof the includedresource objects without having toGET any URLs vialinks.

Resource linkageMUST be represented as one of the following:

Note: The spec does not impart meaning to order of resource identifierobjects in linkage arrays of to-many relationships, although implementationsmay do that. Arrays of resource identifier objects may represent orderedor unordered relationships, and both types can be mixed in one responseobject.

For example, the following article is associated with anauthor:

//...{"type":"articles","id":"1","attributes":{"title":"Rails is Omakase"},"relationships":{"author":{"links":{"self":"http://example.com/articles/1/relationships/author","related":"http://example.com/articles/1/author"},"data":{"type":"people","id":"9"}}},"links":{"self":"http://example.com/articles/1"}}//...

Theauthor relationship includes a link for the relationship itself (whichallows the client to change the related author directly), a related resourcelink to fetch the resource objects, and linkage information.

Resource Links

The optionallinks member within eachresource object containslinksrelated to the resource.

If present, this links objectMAY contain aselflink thatidentifies the resource represented by the resource object.

//...{"type":"articles","id":"1","attributes":{"title":"Rails is Omakase"},"links":{"self":"http://example.com/articles/1"}}//...

A serverMUST respond to aGET request to the specified URL with aresponse that includes the resource as the primary data.

Resource Identifier Objects

A “resource identifier object” is an object that identifies an individualresource.

A “resource identifier object”MUST contain atype member. ItMUSTalso contain anid member, except when it represents a new resource to becreated on the server. In this case, alid memberMUST be included thatidentifies the new resource.

The values of theid,type, andlid membersMUST be strings.

A “resource identifier object”MAY also include ameta member, whose value is ameta object thatcontains non-standard meta-information.

Compound Documents

ServersMAY allow responses that include related resources along with therequested primary resources. Such responses are called “compound documents”.

In a compound document, all included resourcesMUST be represented as anarray ofresource objects in a top-levelincluded member.

Every included resource objectMUST be identified via a chain ofrelationships originating in a document’s primary data. This means thatcompound documents require “full linkage” and that no resource object can beincluded without a direct or indirect relationship to the document’s primarydata.

The only exception to the full linkage requirement is when relationship fieldsthat would otherwise contain linkage data are excluded due tosparse fieldsets requested by the client.

A complete example document with multiple included relationships:

{"data":[{"type":"articles","id":"1","attributes":{"title":"JSON:API paints my bikeshed!"},"links":{"self":"http://example.com/articles/1"},"relationships":{"author":{"links":{"self":"http://example.com/articles/1/relationships/author","related":"http://example.com/articles/1/author"},"data":{"type":"people","id":"9"}},"comments":{"links":{"self":"http://example.com/articles/1/relationships/comments","related":"http://example.com/articles/1/comments"},"data":[{"type":"comments","id":"5"},{"type":"comments","id":"12"}]}}}],"included":[{"type":"people","id":"9","attributes":{"firstName":"Dan","lastName":"Gebhardt","twitter":"dgeb"},"links":{"self":"http://example.com/people/9"}},{"type":"comments","id":"5","attributes":{"body":"First!"},"relationships":{"author":{"data":{"type":"people","id":"2"}}},"links":{"self":"http://example.com/comments/5"}},{"type":"comments","id":"12","attributes":{"body":"I like XML better"},"relationships":{"author":{"data":{"type":"people","id":"9"}}},"links":{"self":"http://example.com/comments/12"}}]}

Acompound documentMUST NOT include more than oneresource object foreachtype andid pair.

Note: In a single document, you can think of thetype andid as acomposite key that uniquely referencesresource objects in another part ofthe document.

Note: For resources that do not contain anid member but do contain alid,thelid is sufficient to establish resource identity and thus linkage betweenresource objects and resource identifier objects throughout the document.

Note: This approach ensures that a single canonicalresource object isreturned with each response, even when the same resource is referencedmultiple times.

Meta Information

Where specified, ameta member can be used to include non-standardmeta-information. The value of eachmeta memberMUST be an object (a“meta object”).

Any membersMAY be specified withinmeta objects.

For example:

{"meta":{"copyright":"Copyright 2015 Example Corp.","authors":["Yehuda Katz","Steve Klabnik","Dan Gebhardt","Tyler Kellen"]},"data":{//...}}

Links

Where specified, alinks member can be used to represent links. The valueof this memberMUST be an object (a “links object”).

Within this object, a linkMUST be represented as either:

A link’s relation typeSHOULD be inferred from the name of the link unless thelink is alink object and the link object has arel member.

A link’s context is thetop-level object,resourceobject, orrelationship object in which itappears.

In the example below, theself link is a string whereas therelated link isalink object. Therelated link object provides additional informationabout the targeted related resource collection as well as a schema that servesas a description document for that collection:

"links":{"self":"http://example.com/articles/1/relationships/comments","related":{"href":"http://example.com/articles/1/comments","title":"Comments","describedby":"http://example.com/schemas/article-comments","meta":{"count":10}}}

Link objects

A “link object” is an object that represents aweb link.

A link objectMUST contain the following member:

  • href: a string whose value is a URI-reference [RFC3986 Section 4.1]pointing to the link’s target.

A link objectMAY also contain any of the following members:

  • rel: a string indicating the link’s relation type. The stringMUST be avalid link relation type.
  • describedby: alink to a description document (e.g. OpenAPI or JSONSchema) for the link target.
  • title: a string which serves as a label for the destination of a linksuch that it can be used as a human-readable identifier (e.g., a menuentry).
  • type: a string indicating the media type of the link’s target.
  • hreflang: a string or an array of strings indicating the language(s) of thelink’s target. An array of strings indicates that the link’s target isavailable in multiple languages. Each stringMUST be a valid language tag[RFC5646].
  • meta: a meta object containing non-standard meta-information about thelink.

Note: thetype andhreflang members are only hints; the target resourceis not guaranteed to be available in the indicated media type or languagewhen the link is actually followed.

JSON:API Object

A JSON:API documentMAY include information about its implementationunder a top leveljsonapi member. If present, the value of thejsonapimemberMUST be an object (a “jsonapi object”).

The jsonapi objectMAY contain any of the following members:

  • version - whose value is a string indicating the highest JSON:API versionsupported.
  • ext - an array of URIs for all appliedextensions.
  • profile - an array of URIs for all appliedprofiles.
  • meta - ameta object that contains non-standard meta-information.

Clients and serversMUST NOT use anext orprofile member for contentnegotiation. Content negotiationMUST only happen based on media typeparameters inContent-Type header.

A simple example appears below:

{"jsonapi":{"version":"1.1","ext":["https://jsonapi.org/ext/atomic"],"profile":["http://example.com/profiles/flexible-pagination","http://example.com/profiles/resource-versioning"]}}

If theversion member is not present, clients should assume the serverimplements at least version 1.0 of the specification.

Note: Because JSON:API is committed to making additive changes only, theversion string primarily indicates which new features a server may support.

Member Names

Implementation and profile defined member names used in a JSON:API documentMUST be treated as case sensitive by clients and servers, and theyMUSTmeet all of the following conditions:

  • Member namesMUST contain at least one character.
  • Member namesMUST contain only the allowed characters listed below.
  • Member namesMUST start and end with a “globally allowed character”,as defined below.

To enable an easy mapping of member names to URLs, it isRECOMMENDED thatmember names use only non-reserved, URL safe characters specified inRFC 3986.

Allowed Characters

The following “globally allowed characters”MAY be used anywhere in a member name:

  • U+0061 to U+007A, “a-z”
  • U+0041 to U+005A, “A-Z”
  • U+0030 to U+0039, “0-9”
  • U+0080 and above (non-ASCII Unicode characters;not recommended, not URL safe)

Additionally, the following characters are allowed in member names, except as thefirst or last character:

  • U+002D HYPHEN-MINUS, “-“
  • U+005F LOW LINE, “_”
  • U+0020 SPACE, “ “(not recommended, not URL safe)

Reserved Characters

The following charactersMUST NOT be used in implementation andprofile defined member names:

  • U+002B PLUS SIGN, “+”(has overloaded meaning in URL query strings)
  • U+002C COMMA, “,”(used as a separator between relationship paths)
  • U+002E PERIOD, “.”(used as a separator within relationship paths)
  • U+005B LEFT SQUARE BRACKET, “[”(used in query parameter families)
  • U+005D RIGHT SQUARE BRACKET, “]”(used in query parameter families)
  • U+0021 EXCLAMATION MARK, “!”
  • U+0022 QUOTATION MARK, ‘”’
  • U+0023 NUMBER SIGN, “#”
  • U+0024 DOLLAR SIGN, “$”
  • U+0025 PERCENT SIGN, “%”
  • U+0026 AMPERSAND, “&”
  • U+0027 APOSTROPHE, “’”
  • U+0028 LEFT PARENTHESIS, “(“
  • U+0029 RIGHT PARENTHESIS, “)”
  • U+002A ASTERISK, “*”
  • U+002F SOLIDUS, “/”
  • U+003A COLON, “:”
  • U+003B SEMICOLON, “;”
  • U+003C LESS-THAN SIGN, “<”
  • U+003D EQUALS SIGN, “=”
  • U+003E GREATER-THAN SIGN, “>”
  • U+003F QUESTION MARK, “?”
  • U+0040 COMMERCIAL AT, “@” (except as first character in@-Members)
  • U+005C REVERSE SOLIDUS, “\”
  • U+005E CIRCUMFLEX ACCENT, “^”
  • U+0060 GRAVE ACCENT, “`”
  • U+007B LEFT CURLY BRACKET, “{“
  • U+007C VERTICAL LINE, “|”
  • U+007D RIGHT CURLY BRACKET, “}”
  • U+007E TILDE, “~”
  • U+007F DELETE
  • U+0000 to U+001F (C0 Controls)

@-Members

Member namesMAY also begin with an at sign (U+0040 COMMERCIAL AT, “@”).Members named this way are called “@-Members”. @-MembersMAY appearanywhere in a document.

This specification provides no guidance on the meaning or usage of @-Members,which are considered to beimplementation semantics. @-MembersMUST be ignored when interpreting this specification’s definitions andprocessing instructions given outside of this subsection. For example, anattribute is defined above as any member of the attributes object.However, because @-Members must be ignored when interpreting that definition, an@-Member that occurs in an attributes object is not an attribute.

Note: Among other things, “@” members can be used to add JSON-LD data to aJSON:API document. Such documents should be served withan extra headerto convey to JSON-LD clients that they contain JSON-LD data.

Extension Members

The name of every new member introduced by an extensionMUST be prefixedwith theextension’s namespace followed by a colon (:).The remainder of the nameMUST adhere to the rules for implementationdefinedmember names.

Fetching Data

Data, including resources and relationships, can be fetched by sending aGET request to an endpoint.

Responses can be further refined with the optional features described below.

Fetching Resources

A serverMUST support fetching resource data for every URL provided as:

  • aself link as part of the top-level links object
  • aself link as part of a resource-level links object
  • arelated link as part of a relationship-level links object

For example, the following request fetches a collection of articles:

GET/articlesHTTP/1.1Accept:application/vnd.api+json

The following request fetches an article:

GET/articles/1HTTP/1.1Accept:application/vnd.api+json

And the following request fetches an article’s author:

GET/articles/1/authorHTTP/1.1Accept:application/vnd.api+json

Responses

200 OK

A serverMUST respond to a successful request to fetch an individualresource or resource collection with a200 OK response.

A serverMUST respond to a successful request to fetch a resourcecollection with an array ofresource objects or an empty array ([]) asthe response document’s primary data.

For example, aGET request to a collection of articles could return:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"http://example.com/articles"},"data":[{"type":"articles","id":"1","attributes":{"title":"JSON:API paints my bikeshed!"}},{"type":"articles","id":"2","attributes":{"title":"Rails is Omakase"}}]}

A similar response representing an empty collection would be:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"http://example.com/articles"},"data":[]}

A serverMUST respond to a successful request to fetch an individualresource with aresource object ornull provided asthe response document’s primary data.

null is only an appropriate response when the requested URL is one thatmight correspond to a single resource, but doesn’t currently.

Note: Consider, for example, a request to fetch a to-one related resource link.This request would respond withnull when the relationship is empty (such thatthe link is corresponding to no resources) but with the single related resource’sresource object otherwise.

For example, aGET request to an individual article could return:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"http://example.com/articles/1"},"data":{"type":"articles","id":"1","attributes":{"title":"JSON:API paints my bikeshed!"},"relationships":{"author":{"links":{"related":"http://example.com/articles/1/author"}}}}}

If the above article’s author is missing, then aGET request to that relatedresource would return:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"http://example.com/articles/1/author"},"data":null}
404 Not Found

A serverMUST respond with404 Not Found when processing a request tofetch a single resource that does not exist, except when the request warrants a200 OK response withnull as the primary data (as described above).

Other Responses

A serverMAY respond with other HTTP status codes.

A serverMAY includeerror details with error responses.

A serverMUST prepare responses, and a clientMUST interpretresponses, in accordance withHTTP semantics.

Fetching Relationships

A serverMUST support fetching relationship data for every relationship URLprovided as aself link as part of a relationship’slinks object.

For example, the following request fetches data about an article’s comments:

GET/articles/1/relationships/commentsHTTP/1.1Accept:application/vnd.api+json

And the following request fetches data about an article’s author:

GET/articles/1/relationships/authorHTTP/1.1Accept:application/vnd.api+json

Responses

200 OK

A serverMUST respond to a successful request to fetch a relationshipwith a200 OK response.

The primary data in the response documentMUST match the appropriatevalue forresource linkage, as described above forrelationship objects.

The top-levellinks objectMAY containself andrelated links,as described above forrelationship objects.

For example, aGET request to a URL from a to-one relationship link couldreturn:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"/articles/1/relationships/author","related":"/articles/1/author"},"data":{"type":"people","id":"12"}}

If the above relationship is empty, then aGET request to the same URL wouldreturn:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"/articles/1/relationships/author","related":"/articles/1/author"},"data":null}

AGET request to a URL from a to-many relationship link could return:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"/articles/1/relationships/tags","related":"/articles/1/tags"},"data":[{"type":"tags","id":"2"},{"type":"tags","id":"3"}]}

If the above relationship is empty, then aGET request to the same URL wouldreturn:

HTTP/1.1200OKContent-Type:application/vnd.api+json{"links":{"self":"/articles/1/relationships/tags","related":"/articles/1/tags"},"data":[]}
404 Not Found

A serverMUST return404 Not Found when processing a request to fetcha relationship link URL that does not exist.

Note: This can happen when the parent resource of the relationshipdoes not exist. For example, when/articles/1 does not exist, request to/articles/1/relationships/tags returns404 Not Found.

If a relationship link URL exists but the relationship is empty, then200 OKMUST be returned, as described above.

Other Responses

A serverMAY respond with other HTTP status codes.

A serverMAY includeerror details with error responses.

A serverMUST prepare responses, and a clientMUST interpretresponses, in accordance withHTTP semantics.

Inclusion of Related Resources

An endpointMAY return resources related to the primary data by default.

An endpointMAY also support aninclude query parameter to allow theclient to customize which related resources should be returned.

If an endpoint does not support theinclude parameter, itMUST respondwith400 Bad Request to any requests that include it.

If an endpoint supports theinclude parameter and a client supplies it:

  • The server’s responseMUST be acompound document with anincluded key — even if thatincluded key holds an empty array (because the requested relationships are empty).
  • The serverMUST NOT include unrequestedresource objects in theincludedsection of thecompound document.

The value of theinclude parameterMUST be a comma-separated (U+002CCOMMA, “,”) list of relationship paths. A relationship path is a dot-separated(U+002E FULL-STOP, “.”) list ofrelationship names. An emptyvalue indicates that no related resources should be returned.

If a server is unable to identify a relationship path or does not supportinclusion of resources from a path, itMUST respond with 400 Bad Request.

Note: For example, a relationship path could becomments.author, wherecomments is a relationship listed under aarticlesresource object, andauthor is a relationship listed under acommentsresource object.

For instance, comments could be requested with an article:

GET/articles/1?include=commentsHTTP/1.1Accept:application/vnd.api+json

In order to request resources related to other resources, a dot-separated pathfor each relationship name can be specified:

GET/articles/1?include=comments.authorHTTP/1.1Accept:application/vnd.api+json

Note: Becausecompound documents require full linkage(except when relationship linkage is excluded by sparse fieldsets), intermediateresources in a multi-part path must be returned along with the leaf nodes. Forexample, a response to a request forcomments.author should includecommentsas well as theauthor of each of thosecomments.

Note: A server may choose to expose a deeply nested relationship such ascomments.author as a direct relationship with an alternative name such ascommentAuthors. This would allow a client to request/articles/1?include=commentAuthors instead of/articles/1?include=comments.author. By exposing the nested relationship withan alternative name, the server can still provide full linkage in compounddocuments without including potentially unwanted intermediate resources.

Multiple related resources can be requested in a comma-separated list:

GET/articles/1?include=comments.author,ratingsHTTP/1.1Accept:application/vnd.api+json

Furthermore, related resources can be requested from a relationship endpoint:

GET/articles/1/relationships/comments?include=comments.authorHTTP/1.1Accept:application/vnd.api+json

In this case, the primary data would be a collection ofresource identifier objects that represent linkage to comments for an article,while the full comments and comment authors would be returned as included data.

Note: This section applies to any endpoint that responds with primarydata, regardless of the request type. For instance, a server could supportthe inclusion of related resources along with aPOST request to create aresource or relationship.

Sparse Fieldsets

A clientMAY request that an endpoint return only specificfields in theresponse on a per-type basis by including afields[TYPE] query parameter.

The value of anyfields[TYPE] parameterMUST be a comma-separated (U+002CCOMMA, “,”) list that refers to the name(s) of the fields to be returned.An empty value indicates that no fields should be returned.

If a client requests a restricted set offields for a given resource type,an endpointMUST NOT include additionalfields in resource objects ofthat type in its response.

If a client does not specify the set offields for a given resource type, theserverMAY send all fields, a subset of fields, or no fields for thatresource type.

GET/articles?include=author&fields[articles]=title,body&fields[people]=nameHTTP/1.1Accept:application/vnd.api+json

Note: The above example URI shows unencoded[ and] characters simply forreadability. In practice, these characters should be percent-encoded. See“Square Brackets in Parameter Names”.

Note: This section applies to any endpoint that responds with resources asprimary or included data, regardless of the request type. For instance, aserver could support sparse fieldsets along with aPOST request to createa resource.

Sorting

A serverMAY choose to support requests to sort resource collectionsaccording to one or more criteria (“sort fields”).

Note: Although recommended, sort fields do not necessarily need tocorrespond to resource attribute and relationship names.

Note: It is recommended that dot-separated (U+002E FULL-STOP, “.”) sortfields be used to request sorting based upon relationship attributes. Forexample, a sort field ofauthor.name could be used to request that theprimary data be sorted based upon thename attribute of theauthorrelationship.

An endpointMAY support requests to sort the primary data with asortquery parameter. The value forsortMUST represent sort fields.

GET/people?sort=ageHTTP/1.1Accept:application/vnd.api+json

An endpointMAY support multiple sort fields by allowing comma-separated(U+002C COMMA, “,”) sort fields. Sort fieldsSHOULD be applied in theorder specified.

GET/people?sort=age,nameHTTP/1.1Accept:application/vnd.api+json

The sort order for each sort fieldMUST be ascending unless it is prefixedwith a minus (U+002D HYPHEN-MINUS, “-“), in which case itMUST be descending.

GET/articles?sort=-created,titleHTTP/1.1Accept:application/vnd.api+json

The above example should return the newest articles first. Any articlescreated on the same date will then be sorted by their title in ascendingalphabetical order.

If the server does not support sorting as specified in the query parametersort, itMUST return400 Bad Request.

If sorting is supported by the server and requested by the client via queryparametersort, the serverMUST return elements of the top-leveldata array of the response ordered according to the criteria specified.The serverMAY apply default sorting rules to top-leveldata ifrequest parametersort is not specified.

Note: This section applies to any endpoint that responds with a resourcecollection as primary data, regardless of the request type.

Pagination

A serverMAY choose to limit the number of resources returned in a responseto a subset (“page”) of the whole set available.

A serverMAY provide links to traverse a paginated data set (“paginationlinks”).

Pagination linksMUST appear in the links object that corresponds to acollection. To paginate the primary data, supply pagination links in thetop-levellinks object. To paginate an included collection returned inacompound document, supply pagination links in the corresponding linksobject.

The following keysMUST be used for pagination links:

  • first: the first page of data
  • last: the last page of data
  • prev: the previous page of data
  • next: the next page of data

KeysMUST either be omitted or have anull value to indicate that aparticular link is unavailable.

Concepts of order, as expressed in the naming of pagination links,MUSTremain consistent with JSON:API’ssorting rules.

Thepagequery parameter family is reserved for pagination. Servers andclientsSHOULD use these parameters for pagination operations.

Note: JSON API is agnostic about the pagination strategy used by a server, butthepage query parameter family can be used regardless of the strategyemployed. For example, a page-based strategy might use query parameters suchaspage[number] andpage[size], while a cursor-based strategy might usepage[cursor].

Note: This section applies to any endpoint that responds with a resourcecollection as primary data, regardless of the request type.

Filtering

Thefilterquery parameter family is reserved for filtering data. Serversand clientsSHOULD use these parameters for filtering operations.

Note: JSON API is agnostic about the strategies supported by a server.

Creating, Updating and Deleting Resources

A serverMAY allow resources of a given type to be created. ItMAYalso allow existing resources to be modified or deleted.

A requestMUST completely succeed or fail (in a single “transaction”). Nopartial updates are allowed.

Note: Thetype member is required in everyresource object throughout requests andresponses in JSON:API. There are some cases, such as whenPOSTing to anendpoint representing heterogeneous data, when thetype could not be inferredfrom the endpoint. However, picking and choosing when it is required would beconfusing; it would be hard to remember when it was required and when it wasnot. Therefore, to improve consistency and minimize confusion,type isalways required.

Creating Resources

A resource can be created by sending aPOST request to a URL that representsa collection of resources. The requestMUST include a singleresource objectas primary data. Theresource objectMUST contain at least atype member.

For instance, a new photo might be created with the following request:

POST/photosHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"photos","attributes":{"title":"Ember Hamster","src":"http://example.com/images/productivity.png"},"relationships":{"photographer":{"data":{"type":"people","id":"9"}}}}}

If a relationship is provided in therelationships member of theresource object, its valueMUST be a relationship object with adatamember. The value of this key represents thelinkage the new resource is tohave.

Client-Generated IDs

A serverMAY accept a client-generated ID along with a request to createa resource. An IDMUST be specified with anid key, the value ofwhichMUST be a universally unique identifier. The clientSHOULD usea properly generated and formattedUUID as described in RFC 4122[RFC4122].

NOTE: In some use-cases, such as importing data from another source, itmay be possible to use something other than a UUID that is still guaranteedto be globally unique. Do not use anything other than a UUID unless you are100% confident that the strategy you are using indeed generates globallyunique identifiers.

For example:

POST/photosHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"photos","id":"550e8400-e29b-41d4-a716-446655440000","attributes":{"title":"Ember Hamster","src":"http://example.com/images/productivity.png"}}}

A serverMUST return403 Forbidden in response to an unsupported requestto create a resource with a client-generated ID.

Responses

201 Created

If the requested resource has been created successfully and the server changesthe resource in any way (for example, by assigning anid), the serverMUSTreturn a201 Created response and a document that contains the resource asprimary data.

The responseSHOULD include aLocation header identifying the locationof the newly created resource, in order to comply withRFC7231.

If theresource object returned by the response contains aself key in itslinks member and aLocation header is provided, the value of theselfmemberMUST match the value of theLocation header.

HTTP/1.1201CreatedLocation:http://example.com/photos/550e8400-e29b-41d4-a716-446655440000Content-Type:application/vnd.api+json{"data":{"type":"photos","id":"550e8400-e29b-41d4-a716-446655440000","attributes":{"title":"Ember Hamster","src":"http://example.com/images/productivity.png"},"links":{"self":"http://example.com/photos/550e8400-e29b-41d4-a716-446655440000"}}}

A serverMAY return a201 Created response with a document that containsno primary data if the requested resource has been created successfully and theserver does not change the resource in any way (for example, by assigning anid orcreatedAt attribute). Other top-level members, such asmeta, couldbe included in the response document.

Note: Only servers that acceptClient-GeneratedIDs can avoid assigning anid to a new resource.

202 Accepted

If a request to create a resource has been accepted for processing, but theprocessing has not been completed by the time the server responds, theserverMUST return a202 Accepted status code.

204 No Content

If the requested resource has been created successfully and the server does notchange the resource in any way (for example, by assigning anid orcreatedAtattribute), the serverMUST return either a201 Created status code andresponse document (as described above) or a204 No Content status code with noresponse document.

403 Forbidden

A serverMAY return403 Forbidden in response to an unsupported requestto create a resource.

404 Not Found

A serverMUST return404 Not Found when processing a request thatreferences a related resource that does not exist.

409 Conflict

A serverMUST return409 Conflict when processing aPOST request tocreate a resource with a client-generated ID that already exists.

A serverMUST return409 Conflict when processing aPOST request inwhich theresource object’stype is not among the type(s) that constitute thecollection represented by the endpoint.

A serverSHOULD include error details and provide enough information torecognize the source of the conflict.

Other Responses

A serverMAY respond with other HTTP status codes.

A serverMAY includeerror details with error responses.

A serverMUST prepare responses, and a clientMUST interpretresponses, in accordance withHTTP semantics.

Updating Resources

A resource can be updated by sending aPATCH request to the URL thatrepresents the resource.

The URL for a resource can be obtained in theself link of the resourceobject. Alternatively, when aGET request returns a singleresource object asprimary data, the same request URL can be used for updates.

ThePATCH requestMUST include a singleresource object as primary data.Theresource objectMUST containtype andid members.

For example:

PATCH/articles/1HTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"articles","id":"1","attributes":{"title":"To TDD or Not"}}}

Updating a Resource’s Attributes

Any or all of a resource’sattributesMAY be included in the resourceobject included in aPATCH request.

If a request does not include all of theattributes for a resource, the serverMUST interpret the missingattributes as if they were included with theircurrent values. The serverMUST NOT interpret missing attributes asnullvalues.

For example, the followingPATCH request is interpreted as a request toupdate only thetitle andtext attributes of an article:

PATCH/articles/1HTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"articles","id":"1","attributes":{"title":"To TDD or Not","text":"TLDR; It's complicated... but check your test coverage regardless."}}}

Updating a Resource’s Relationships

Any or all of a resource’srelationshipsMAY be included in the resourceobject included in aPATCH request.

If a request does not include all of therelationships for a resource, the serverMUST interpret the missingrelationships as if they were included with theircurrent values. ItMUST NOT interpret them asnull or empty values.

If a relationship is provided in therelationships member of a resourceobject in aPATCH request, its valueMUST be a relationship objectwith adata member. The relationship’s value will be replaced with thevalue specified in this member.

For instance, the followingPATCH request will update theauthor relationship of an article:

PATCH/articles/1HTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"articles","id":"1","relationships":{"author":{"data":{"type":"people","id":"1"}}}}}

Likewise, the followingPATCH request performs a complete replacement ofthetags for an article:

PATCH/articles/1HTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"articles","id":"1","relationships":{"tags":{"data":[{"type":"tags","id":"2"},{"type":"tags","id":"3"}]}}}}

A serverMAY reject an attempt to do a full replacement of a to-manyrelationship. In such a case, the serverMUST reject the entire update,and return a403 Forbidden response.

Note: Since full replacement may be a very dangerous operation, a servermay choose to disallow it. For example, a server may reject full replacement ifit has not provided the client with the full list of associated objects, anddoes not want to allow deletion of records the client has not seen.

Responses

200 OK

If a server accepts an update but also changes the targeted resource in waysother than those specified by the request (for example, updating theupdatedAt attribute or a computedsha), itMUST return a200 OKresponse and a document that contains the updated resource as primary data.

A serverMAY return a200 OK response with a document that contains noprimary data if an update is successful and the server does not change thetargeted resource in ways other than those specified by the request. Othertop-level members, such asmeta, could be included in the response document.

202 Accepted

If an update request has been accepted for processing, but the processinghas not been completed by the time the server responds, the serverMUSTreturn a202 Accepted status code.

204 No Content

If an update is successful and the server doesn’t change the targetedresource in ways other than those specified by the request, the serverMUST return either a200 OK status code and response document (asdescribed above) or a204 No Content status code with no response document.

403 Forbidden

A serverMUST return403 Forbidden in response to an unsupported requestto update a resource or relationship.

404 Not Found

A serverMUST return404 Not Found when processing a request to modifya resource that does not exist.

A serverMUST return404 Not Found when processing a request thatreferences a related resource that does not exist.

409 Conflict

A serverMAY return409 Conflict when processing aPATCH request toupdate a resource if that update would violate other server-enforcedconstraints (such as a uniqueness constraint on a property other thanid).

A serverMUST return409 Conflict when processing aPATCH request inwhich the resource object’stype orid do not match the server’s endpoint.

A serverSHOULD include error details and provide enough information torecognize the source of the conflict.

Other Responses

A serverMAY respond with other HTTP status codes.

A serverMAY includeerror details with error responses.

A serverMUST prepare responses, and a clientMUST interpretresponses, in accordance withHTTP semantics.

Updating Relationships

Although relationships can be modified along with resources (as describedabove), JSON:API also supports updating of relationships independently atURLs fromrelationship links.

Note: Relationships are updated without exposing the underlying serversemantics, such as foreign keys. Furthermore, relationships can be updatedwithout necessarily affecting the related resources. For example, if an articlehas many authors, it is possible to remove one of the authors from the articlewithout deleting the person itself. Similarly, if an article has many tags, itis possible to add or remove tags. Under the hood on the server, the firstof these examples might be implemented with a foreign key, while the secondcould be implemented with a join table, but the JSON:API protocol would bethe same in both cases.

Note: A server may choose to delete the underlying resource if arelationship is deleted (as a garbage collection measure).

Updating To-One Relationships

A to-one relationship can be updated by sending aPATCH request to a URLfrom a to-onerelationship link.

ThePATCH requestMUST include a top-level member nameddata containingone of:

For example, the following request updates the author of an article:

PATCH/articles/1/relationships/authorHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":{"type":"people","id":"12"}}

And the following request clears the author of the same article:

PATCH/articles/1/relationships/authorHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":null}

If the relationship is updated successfully then the serverMUST returna successful response.

Updating To-Many Relationships

A to-many relationship can be updated by sending aPATCH,POST, orDELETE request to a URL from a to-manyrelationship link.

For all request types, the bodyMUST contain adata member whose valueis an empty array or an array ofresource identifier objects.

If a client makes aPATCH request to a URL from a to-manyrelationship link, the serverMUST either completelyreplace every member of the relationship, return an appropriate error responseif some resources cannot be found or accessed, or return a403 Forbiddenresponse if complete replacement is not allowed by the server.

For example, the following request replaces every tag for an article:

PATCH/articles/1/relationships/tagsHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":[{"type":"tags","id":"2"},{"type":"tags","id":"3"}]}

And the following request clears every tag for an article:

PATCH/articles/1/relationships/tagsHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":[]}

If a client makes aPOST request to a URL from arelationship link, the serverMUST add the specifiedmembers to the relationship unless they are already present. If a giventypeandid is already in the relationship, the serverMUST NOT add it again.

Note: This matches the semantics of databases that use foreign keys forhas-many relationships. Document-based storage should check the has-manyrelationship before appending to avoid duplicates.

If all of the specified resources can be added to, or are already presentin, the relationship then the serverMUST return a successful response.

Note: This approach ensures that a request is successful if the server’sstate matches the requested state, and helps avoid pointless race conditionscaused by multiple clients making the same changes to a relationship.

In the following example, the comment with ID123 is added to the list ofcomments for the article with ID1:

POST/articles/1/relationships/commentsHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":[{"type":"comments","id":"123"}]}

If the client makes aDELETE request to a URL from arelationship link the serverMUST delete the specifiedmembers from the relationship or return a403 Forbidden response. If all ofthe specified resources are able to be removed from, or are already missingfrom, the relationship then the serverMUST return a successful response.

Note: As described above forPOST requests, this approach helps avoidpointless race conditions between multiple clients making the same changes.

Relationship members are specified in the same way as in thePOST request.

In the following example, comments with IDs of12 and13 are removedfrom the list of comments for the article with ID1:

DELETE/articles/1/relationships/commentsHTTP/1.1Content-Type:application/vnd.api+jsonAccept:application/vnd.api+json{"data":[{"type":"comments","id":"12"},{"type":"comments","id":"13"}]}

Note: RFC 7231 specifies that a DELETE request may include a body, butthat a server may reject the request. This spec defines the semantics of aserver, and we are defining its semantics for JSON:API.

Responses

200 OK

If a server accepts an update but also changes the targeted relationship inother ways than those specified by the request, itMUST return a200 OKresponse and a document that includes the updated relationship data as itsprimary data.

A serverMAY return a200 OK response with a document that contains noprimary data if an update is successful and the server does not change thetargeted relationship in ways other than those specified by the request. Othertop-level members, such asmeta, could be included in the response document.

202 Accepted

If a relationship update request has been accepted for processing, but theprocessing has not been completed by the time the server responds, theserverMUST return a202 Accepted status code.

204 No Content

If an update is successful and the server doesn’t change the targetedrelationship in ways other than those specified by the request, the serverMUST return either a200 OK status code and response document (asdescribed above) or a204 No Content status code with no response document.

Note: This is the appropriate response to aPOST request sent to a URLfrom a to-manyrelationship link when that relationship alreadyexists. It is also the appropriate response to aDELETE request sent to a URLfrom a to-manyrelationship link when that relationship doesnot exist.

403 Forbidden

A serverMUST return403 Forbidden in response to an unsupported requestto update a relationship.

Other Responses

A serverMAY respond with other HTTP status codes.

A serverMAY includeerror details with error responses.

A serverMUST prepare responses, and a clientMUST interpretresponses, in accordance withHTTP semantics.

Deleting Resources

A resource can be deleted by sending aDELETE request to the URLthat represents the resource:

DELETE/photos/1HTTP/1.1Accept:application/vnd.api+json

Responses

200 OK

A serverMAY return a200 OK response with a document that contains noprimary data if a deletion request is successful. Other top-level members, suchasmeta, could be included in the response document.

202 Accepted

If a deletion request has been accepted for processing, but the processing hasnot been completed by the time the server responds, the serverMUSTreturn a202 Accepted status code.

204 No Content

If a deletion request is successful, the serverMUST return either a200OK status code and response document (as described above) or a204 No Contentstatus code with no response document.

404 NOT FOUND

A serverSHOULD return a404 Not Found status code if a deletion request failsdue to the resource not existing.

Other Responses

A serverMAY respond with other HTTP status codes.

A serverMAY includeerror details with error responses.

A serverMUST prepare responses, and a clientMUST interpretresponses, in accordance withHTTP semantics.

Query Parameters

Query Parameter Families

Although “query parameter” is a common term in everyday web development, it isnot a well-standardized concept. Therefore, JSON:API provides its owndefinition of a query parameter.

For the most part, JSON:API’s definition coincides with colloquial usage, and itsdetails can be safely ignored. However, one important consequence of thisdefinition is that a URL like the following is considered to have two distinctquery parameters:

/?page[offset]=0&page[limit]=10

The two parameters are namedpage[offset] andpage[limit]; there is nosinglepage parameter.

In practice, however, parameters likepage[offset] andpage[limit] areusually defined and processed together, and it’s convenient to refer to themcollectively. Therefore, JSON:API introduces the concept of a query parameterfamily.

A “query parameter family” is the set of all query parameters whose name startswith a “base name”, followed by zero or more instances of empty square brackets(i.e.[]), square-bracketed legalmember names, or square-bracketeddot-separated lists of legal member names. The family is referred toby its base name.

For example, thefilter query parameter family includes parameters named:filter,filter[x],filter[],filter[x][],filter[][],filter[x][y],filter[x.y], etc. However,filter[_] is not a valid parameter name in thefamily, because_ is not a validmember name.

Note: Dot separated lists of legal member names are intended to be used forrelationship paths. For example, this allows filtering strategies usingrelationship paths as defined forsorting in query parameterssuch asGET /posts?sort=author.name&filter[author.status]=active.

Extension-Specific Query Parameters

The base name of every query parameter introduced by an extensionMUST beprefixed with the extension’s namespace followed by a colon (:). Theremainder of the base nameMUST contain only the characters [a-z] (U+0061to U+007A, “a-z”).

Implementation-Specific Query Parameters

ImplementationsMAY support custom query parameters. However, the names ofthese query parametersMUST come from afamilywhose base name is a legalmember name and also contains at leastone non a-z character (i.e., outside U+0061 to U+007A).

It isRECOMMENDED that a capital letter (e.g. camelCasing) be used tosatisfy the above requirement.

If a server encounters a query parameter that does not follow the namingconventions above, or the server does not know how to process it as a queryparameter from this specification, itMUST return400 Bad Request.

Note: By forbidding the use of query parameters that contain only the characters[a-z], JSON:API is reserving the ability to standardize additional queryparameters later without conflicting with existing implementations.

Errors

Processing Errors

A serverMAY choose to stop processing as soon as a problem is encountered,or itMAY continue processing and encounter multiple problems. For instance,a server might process multiple attributes and then return multiple validationproblems in a single response.

When a server encounters multiple problems for a single request, the mostgenerally applicable HTTP error codeSHOULD be used in the response. Forinstance,400 Bad Request might be appropriate for multiple 4xx errorsor500 Internal Server Error might be appropriate for multiple 5xx errors.

Error Objects

Error objects provide additional information about problems encountered whileperforming an operation. Error objectsMUST be returned as an arraykeyed byerrors in the top level of a JSON:API document.

An error objectMAY have the following members, andMUST contain atleast one of:

  • id: a unique identifier for this particular occurrence of the problem.
  • links: alinks object thatMAY contain the following members:
    • about: alink that leads to further details about thisparticular occurrence of the problem. When dereferenced, this URISHOULDreturn a human-readable description of the error.
    • type: alink that identifies the type of error that thisparticular error is an instance of. This URISHOULD be dereferenceable toa human-readable explanation of the general error.
  • status: the HTTP status code applicable to this problem, expressed as astring value. ThisSHOULD be provided.
  • code: an application-specific error code, expressed as a string value.
  • title: a short, human-readable summary of the problem thatSHOULD NOTchange from occurrence to occurrence of the problem, except for purposes oflocalization.
  • detail: a human-readable explanation specific to this occurrence of theproblem. Liketitle, this field’s value can be localized.
  • source: an object containing references to the primary source of the error.ItSHOULD include one of the following members or be omitted:
    • pointer: a JSON Pointer [RFC6901]to the value in the request document that caused the error [e.g."/data"for a primary data object, or"/data/attributes/title" for a specificattribute]. ThisMUST point to a value in the request document thatexists; if it doesn’t, the clientSHOULD simply ignore the pointer.
    • parameter: a string indicating which URI query parameter causedthe error.
    • header: a string indicating the name of a single request header whichcaused the error.
  • meta: ameta object containing non-standard meta-information about theerror.

Appendix

Query Parameters Details

Parsing/Serialization

A query parameter is a name–value pair extracted from, or serialized into, aURI’s query string.

To extract the query parameters from a URI, an implementationMUST run theURI’s query string, excluding the leading question mark, through theapplication/x-www-form-urlencoded parsing algorithm,with one exception: JSON:API allows the specification that defines a queryparameter’s usage to provide its own rules for parsing the parameter’s valuefrom thevalue bytes identified in steps 3.2 and and 3.3 of theapplication/x-www-form-urlencodedparsing algorithm. The resulting value might not be a string.

Note: In general, the query string parsing built in to servers and browserswill match the process specified above, so most implementations do not needto worry about this.

Theapplication/x-www-form-urlencoded format is referenced because it isthe basis for thea=b&c=d style that almost all query strings use today.

However,application/x-www-form-urlencoded parsing contains the bizarrehistorical artifact that+ characters must be treated as spaces, and itrequires that all values be percent-decoded during parsing, which makes itimpossible to useRFC 3986 delimiter charactersas delimiters. These issues motivate the exception that JSON:API defines above.

Similarly, to serialize a query parameter into a URI, an implementationMUSTusetheapplication/x-www-form-urlencoded serializer,with the corresponding exception that a parameter’s value — but not its name —may be serialized differently than that algorithm requires, provided theserialization does not interfere with the ability to parse back the resulting URI.

Square Brackets in Parameter Names

Withquery parameter families, JSON:API allows forquery parameters whose names contain square brackets (i.e., U+005B “[” andU+005D “]”).

According to the query parameter serialization rules above, a compliantimplementation will percent-encode these square brackets. However, some URIproducers — namely browsers — do not always encode them. ServersSHOULDaccept requests in which these square brackets are left unencoded in a queryparameter’s name. If a server does accept these requests, itMUST treat therequest as equivalent to one in which the square brackets were percent-encoded.


[8]ページ先頭

©2009-2026 Movatter.jp