Making API calls with Apollo client in AndroidNov 16, 2019
GraphQL is a query Language for your API
It is an alternative for the REST APIs. It is not specific for a single platform and works for all type of clients including Android, iOS or web. It stands between your server and client and helps you to query your data in a more optimized way.
GraphQL helps to address some of the headaches developers face when developing a REST-API and when consuming REST-API
To use GrahpQL on Android you need the Apollo-client. It’s the only client that allows you to consume graphQL data. It will take care of requesting and caching your data, as well as updating your UI.
Features of GraphQL
- Client, driven, you only get what you want
- Avoid doing multiple calls. Incase of rest we have to maintain multiple endpoints
- Universally compatible. Use any build setup and any GRAPHQL API
- Better network performance
- Community driven
URL Routes vs GraphQL Schema
An API isn’t useful if it isn’t predictable.
In GraphQL, you don’t use URLs to identify what is available in the API. Instead, you use a GraphQL schema:
Who is using GraphQL?
Graphcool is a service that gives you a graphql server
The Schema is the contract between the server and the client
- Step 1 npm install
- Step 2 npm install apollo-codegen
- Step 3 Generate Schema apollo-codegen download-schema link-to-url-endpoint --output schema.json
Now make a file with
.graphql queries and add following queries:
Make a directory with name “graphql”under the /main of your project in the same level of java directory and paste both the files. Now rebuild your project and when the build is successful you will see auto generated models in build/generated like shown in following screenshot:
Setting up Apollo client
Apollo-android uses okhttp client for requesting the queries and getting response.
Querying from the client - CreatePost
Querying from the client - getAllPost
You can get the source code here