Using the models without apollo-runtime
apollo-runtime
and ApolloClient
provide support for doing the network requests and interacting with the cache, but you can use the generated models and parsers without the runtime and use your network layer of choice for the HTTP calls.
For this, remove the com.apollographql.apollo:apollo-runtime
dependency and replace it with:
Kotlin
build.gradle
1implementation("com.apollographql.apollo:apollo-api:4.1.0")
Composing an HTTP request body
To compose an HTTP POST request body to be sent to your server, use composeJsonRequest
:
Kotlin
1/**
2 * jsonRequest contains data to be sent to the server
3 * {
4 * "query": ...
5 * "variables": ...
6 * "extensions": ...
7 * }
8 */
9val body = buildJsonString {
10 query.composeJsonRequest(this, customScalarAdapters)
11}
12
13/**
14 * Send it to your backend
15 */
16val httpResponse = sendHttpRequest(
17 "POST",
18 "https://com.example/graphql",
19 "application/json",
20 body
21)
Parsing an HTTP response body
To parse a network response into the type safe models, use parseJsonResponse
:
Kotlin
1/**
2 * jsonResponse should contain a json with data and possibly errors:
3 *
4 * {
5 * "data": ...
6 * "errors": ...
7 * "extensions": ...
8 * }
9 **/
10val jsonReader = httpResponse.body.source().buffer().jsonReader()
11val response = operation.parseJsonResponse(jsonReader)
12
13println(response.data)
Composing an HTTP response body
For your integration tests, you can also compose a complete response from a programmatically built data
. For this, use composeJsonResponse
:
Kotlin
1/**
2 * Build a fake data object
3 **/
4val data = SomeQuery.Data(...)
5
6/**
7 * jsonResponse contains a json with data and possibly errors:
8 * {
9 * "data": ...
10 * "errors": ...
11 * "extensions": ...
12 * }
13 **/
14val jsonResponse = buildJsonString {
15 operation.composeJsonResponse(this, data)
16}
17
18mockServer.enqueue(jsonResponse)