Subscriptions

The Chargetrip API leverages GraphQL technology and uses different types of operations. Queries and mutations handle immediate requests and responses. Subscriptions are used for long-lasting operations and can send multiple updates over time. These subscriptions are managed via a websocket, which requires a different method for authentication and communication compared to regular queries or mutations.

Note

Subscriptions work out of the box in most GraphQL clients. In this guide you will learn how to communicate with websockets using the terminal. Since the terminal does not support websockets out of the box a library called wscat will be used. It is open-source and can be downloaded here.

Step 1

Initialize

To get started, initialize a connection and set the correct WebSocket protocol. The Chargetrip API supports the the graphql-transport-ws Sec-WebSocket-Protocol.

Make sure to configure this protocol correctly to establish a successful connection.

Step 2

Authorize

Authorize the connection by sending a message with your credentials. On success you will receive the following response: { "type": "connection_ack" }.

Step 3

Communicate

After authorization, start sending subscriptions and receiving data. To send a subscription, add an id to any unique identifier in the message. That exact id will be returned to ensure that the right message was received.

For example, consider the routeUpdatedById subscription with the status field.

Once everything is properly set up and a routeId is correctly specified in the variables and query, the WebSocket will respond with an object containing 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.

Step 4

Close

After retrieving the desired results, the connection can be closed by pressing ctrl + c or cmd + c in the terminal.