Skip to content

🤖 A strongly-typed, caching GraphQL client for the JVM, Android and Kotlin native

License

Notifications You must be signed in to change notification settings

codyteng/apollo-android

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Apollo GraphQL Client for Android and the JVM

GitHub license Join Spectrum CI GitHub release

Apollo Android is a GraphQL client that generates Java and Kotlin models from GraphQL queries. These models give you a type-safe API to work with GraphQL servers. Apollo helps you keep your GraphQL query statements together, organized, and easy to access. When you change a query and recompile your project, Apollo codegen rebuilds your data model. Code generation also allows Apollo to read and unmarshal responses from the network without the need for any reflection.

This library is designed primarily with Android in mind, but you can use it in any Java/Kotlin app. All Android-specific functionality (such as using SQLite as a cache or the Android main thread for callbacks) is in apollo-android-support.

Features

  • Automatic generation of typesafe models
  • Support for Java and Kotlin code generation
  • Queries, Mutations and Subscriptions
  • Reflection-free parsing of responses
  • HTTP cache
  • Normalized cache
  • File uploads
  • Custom scalar types
  • Support for RxJava2, RxJava3, and Coroutines

Adding Apollo to your Project

The latest Gradle plugin version is Download

In your module Gradle file, apply the com.apollographql.apollo plugin and add the Apollo dependencies:

plugins {
  id("com.apollographql.apollo").version("x.y.z")
}

repositories {
  jcenter()
}

dependencies {
  implementation("com.apollographql.apollo:apollo-runtime:x.y.z")

  // optional: if you want to use the normalized cache
  implementation("com.apollographql.apollo:apollo-normalized-cache-sqlite:x.y.z")
  // optional: for coroutines support
  implementation("com.apollographql.apollo:apollo-coroutines-support:x.y.z")
  // optional: for RxJava3 support  
  implementation("com.apollographql.apollo:apollo-rx3-support:x.y.z")

  // optional: if you just want the generated models and parser write your own HTTP code/cache code   
  implementation("com.apollographql.apollo:apollo-api:x.y.z")
}

Downloading a schema.json file

Apollo Android requires your GraphQL server's schema as a schema.json file. You can obtain the contents of this file by running an introspection query on your server.

The Apollo Gradle plugin exposes a downloadApolloSchema task to help you obtain your schema. Provide this task your server's GraphQL endpoint and the output location for the schema.json file:

./gradlew downloadApolloSchema -Pcom.apollographql.apollo.endpoint=https://your.graphql.endpoint -Pcom.apollographql.apollo.schema=src/main/graphql/com/example/schema.json

If your GraphQL endpoint requires authentication, you can pass custom HTTP headers:

./gradlew downloadApolloSchema -Pcom.apollographql.apollo.endpoint=https://your.graphql.endpoint -Pcom.apollographql.apollo.schema=src/main/graphql/com/example/schema.json  "-Pcom.apollographql.apollo.headers=Authorization=Bearer YOUR_TOKEN" "-Pcom.apollographql.apollo.query_params=key1=value1&key2=value2"

Generating models from your queries

  1. Create a directory for your GraphQL files like you would do for Java/Kotlin: src/main/graphql/com/example/. Apollo Android will generate models in the com.apollographql.apollo.sample package.
  2. Add your schema.json to the directory at src/main/graphql/com/example/schema.json. If you don't have a schema.json file yet, see Downloading a schema.json file.
  3. Put each of your client's GraphQL queries in its own .graphql file, such as src/main/graphql/com/example/LaunchDetails.graphql for the following query:
query LaunchDetails($id:ID!) {
  launch(id: $id) {
    id
    site
    mission {
      name
      missionPatch(size:LARGE)
    }
  }
}
  1. Specify whether you want to generate Kotlin or Java models:
apollo {
  generateKotlinModels.set(true) // or false for Java models
}
  1. Build your project to generate models from your queries. In the case of the example query above, this generates a LaunchDetailsQuery Java or Kotlin source file.

Executing queries

You use an instance of the ApolloClient class to interact with your server and cache.

To make a query using your generated models:

val apolloClient = ApolloClient.builder()
                .serverUrl("https://")
                .build()

            apolloClient.query(LaunchDetailsQuery(id = "83"))
                .enqueue(object : ApolloCall.Callback<LaunchDetailsQuery.Data>() {
                    override fun onFailure(e: ApolloException) {
                        Log.e("Apollo", "Error", e)
                    }

                    override fun onResponse(response: Response<LaunchDetailsQuery.Data>) {
                        Log.e("Apollo", "Launch site: ${response.data?.launch?.site}")
                    }
                })

Custom scalar types

Apollo supports custom scalar types, such as Date.

You first need to define the mapping in your build.gradle file. This maps from the GraphQL type to the Java/Kotlin class to use in code.

// Java
apollo {
  customTypeMapping = [
    "Date" : "java.util.Date"
  ]
}

// Kotlin
apollo {
    customTypeMapping.set(mapOf(
        "Date" to "java.util.Date"
    ))
}

Next, register your custom adapter and add it to your ApolloClient builder:

    val dateCustomTypeAdapter = object : CustomTypeAdapter<Date> {
         override fun decode(value: CustomTypeValue<*>): Date {
             return try {
                 DATE_FORMAT.parse(value.value.toString())
             } catch (e: ParseException) {
                 throw RuntimeException(e)
             }
         }
    
         override fun encode(value: Date): CustomTypeValue<*> {
             return GraphQLString(DATE_FORMAT.format(value))
         }
     }
    
     ApolloClient.builder()
         .serverUrl(serverUrl)
         .addCustomTypeAdapter(CustomType.DATE, dateCustomTypeAdapter)
         .build()

IntelliJ Plugin

The JS Graphql IntelliJ Plugin provides auto-completion, error highlighting, and go-to-definition functionality for your .graphql files. You can create a .graphqlconfig file to use GraphQL scratch files to work with your schema outside product code (such as to write temporary queries to test resolvers).

Releases

Our changelog has the release history.

Releases are hosted on jcenter.

Latest development changes are available in Sonatype's snapshots repository:

  repositories {
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
  }

Advanced topics

Advanced topics are available in the official docs:

Contributing

If you'd like to contribute, please see Contributing.md.

License

The MIT License (MIT)

Copyright (c) 2020 Meteor Development Group, Inc.

About

🤖 A strongly-typed, caching GraphQL client for the JVM, Android and Kotlin native

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 57.3%
  • Kotlin 42.6%
  • Other 0.1%