JSON:API is a specification for building APIs in JSON.
Quick usage example:
import 'package:http/http.dart';
import 'package:json_api/json_api.dart';
void main() async {
final httpClient = Client();
final jsonApiClient = JsonApiClient(httpClient);
final companiesUri = Uri.parse('http://localhost:8080/companies');
final response = await jsonApiClient.fetchCollection(companiesUri);
httpClient.close();
print('Status: ${response.status}');
print('Headers: ${response.headers}');
final resource = response.data.unwrap().first;
print('The collection page size is ${response.data.collection.length}');
print('The first element is ${resource}');
print('Attributes:');
resource.attributes.forEach((k, v) => print('$k=$v'));
print('Relationships:');
resource.toOne.forEach((k, v) => print('$k=$v'));
resource.toMany.forEach((k, v) => print('$k=$v'));
}
To see this in action:
- start the server:
$ dart example/cars_server.dart
Listening on 127.0.0.1:8080
- run the script:
$ dart example/fetch_collection.dart
Status: 200
Headers: {x-frame-options: SAMEORIGIN, content-type: application/vnd.api+json, x-xss-protection: 1; mode=block, x-content-type-options: nosniff, transfer-encoding: chunked, access-control-allow-origin: *}
The collection page size is 1
The first element is Resource(companies:1)
Attributes:
name=Tesla
nasdaq=null
updatedAt=2019-07-07T13:08:18.125737
Relationships:
hq=Identifier(cities:2)
models=[Identifier(models:1), Identifier(models:2), Identifier(models:3), Identifier(models:4)]
The client provides a set of methods to deal with resources and relationships.
- Fetching
- fetchCollection - resource collection, either primary or related
- fetchResource - a single resource, either primary or related
- fetchRelationship - a generic relationship (either to-one, to-many or even incomplete)
- fetchToOne - a to-one relationship
- fetchToMany - a to-many relationship
- Manipulating resources
- createResource - creates a new primary resource
- updateResource - updates the existing resource by its type and id
- deleteResource - deletes the existing resource
- Manipulating relationships
- replaceToOne - replaces the existing to-one relationship with a new resource identifier
- deleteToOne - deletes the existing to-one relationship by setting the resource identifier to null
- replaceToMany - replaces the existing to-many relationship with the given set of resource identifiers
- addToMany - adds the given identifiers to the existing to-many relationship
These methods accept the target URI and the object to update (except for fetch and delete requests). You can also pass an optional map of HTTP headers, e.g. for authentication. The return value is a Response object.
You can get the status of the Response from either Response.status or one of the following properties:
The Response also contains the raw Response.status and a map of HTTP headers. Two headers used by JSON:API can be accessed directly for your convenience:
- Response.location holds the
Location
header used in creation requests - Response.contentLocation holds the
Content-Location
header used for Asynchronous Processing
The most important part of the Response is the Response.document containing the JSON:API document sent by the server (if any). If the document has the Primary Data, you can use Response.data shortcut to access it directly.
If you requested related resources to be included in the response (see Compound Documents) and the server fulfilled your request, the PrimaryData.included property will contain them.
For unsuccessful operations the Response.data property will be null. If the server decided to include the error details in the response, those can be found in the Document.errors property.
Some servers may support Asynchronous Processing.
When the server responds with 202 Accepted
, the client expects the Primary Data to always be a Resource (usually
representing a job queue). In this case, Response.document and Response.data will be null. Instead,
the response document will be placed to Response.asyncDocument (and Response.asyncData).
Also in this case the Response.contentLocation
will point to the job queue resource. You can fetch the job queue resource periodically and check
the type of the returned resource. Once the operation is complete, the request will return the created resource.
The server included in this package is still under development. It is not suitable for real production environment yet except maybe for really simple demo or testing cases.