You are viewing documentation for a previous version of this software.

Switch to the latest stable version.

Using the models without apollo-runtime


apollo-runtime and ApolloClient provides 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.apollo3:apollo-runtime dependency and replace it with:

Kotlin
build.gradle
1implementation("com.apollographql.apollo3:apollo-api:3.8.5")

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 *  "data": ...
5 *  "errors": ...
6 *  "extensions": ...
7 * }
8 **/
9val jsonReader = httpResponse.body.source().buffer().jsonReader()
10val response = operation.parseJsonResponse(jsonReader)
11
12println(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)
Feedback

Edit on GitHub

Forums