Subscriptions
The Chargetrip API relies on GraphQL technology, so some requests use a subscription mechanism. Unlike queries or mutations, subscriptions are long-lasting operations and can change their result over time. These operations are handled by a websocket. Authenticating and communicating with this websocket is different than a regular query or mutation.
Step 1
Initialize the websocket
To get started with the websocket, initialize a connection. It is important to set the correct WebSocket protocol. We support the graphql-ws and the graphql-transport-ws as Sec-WebSocket-Protocol. The latter is preferred, as described over here. Each of these protocols uses a different base url.
Subscriptions / Initialise using graphql-transport-ws
- 01
wscat -c wss://api.chargetrip.io/subscription -s graphql-transport-ws
Subscriptions / Initialise using graphql-ws
- 01
wscat -c wss://api.chargetrip.io/graphql -s graphql-ws
Step 2
Authorization on the websocket
Once a connection has been opened, authorization needs to be set up. This can be done by sending a message with the correct type and payload. The type will need to be init and the payload must contain an x-client-id and an x-app-id. If everything was successful, the websocket returns; { "type": "connection_ack" }.
Subscriptions / Authorization payload
- 01
- 02
- 03
- 04
- 05
- 06
{
"type":"connection_init",
"payload": {
"x-client-id": "Your x-client-id here"
}
}
Step 3
Communicating on the websocket
After authorization, start sending subscriptions and receiving data. To send a subscription, add an id to any unique identifier in the message. The id will be returned to ensure that the right message was received.
To illustrate how this works, the routeUpdatedById subscription with the status field is being sent.
Once everything is properly set-up and a routeId was correctly set in the variables and query, the WebSocket will respond with an object that contains the status. For more information about the route subscription and responses have a look at the route section. If a routeId is not set in the variables, there will be no response from the server.
Depending on websocket protocol the message type needs to be either start or subscription.
Subscriptions / Communicating
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
{
"id": "1",
"type": "start",
"payload": {
"query": "subscription routeUpdatedById { routeUpdatedById(id: \"A route id here\") { status } }"
},
"variables": {
"id": "A route id here"
}
}
Step 4
Closing the connection
After getting the desired results, the connection can be closed by pressing ctrl + c or cmd + c in a terminal.