Get started with Apollo iOS codegen
This short tutorial guides you through the basic concepts of generating Swift code with Apollo iOS. We'll introduce you the core capabilities of code generation, and walk through the process of generating Swift code using a GraphQL schema and GraphQL operations.
For more in-depth details, see
Step 1: Project Setup
Start by creating a new directory, and navigating into it:
mkdir ios-code-gen-examplecd ios-code-gen-example
Step 2: Download a GraphQL schema
We'll use the
On the right-hand side in Apollo Studio find the drop-down to download the schema, shown in the above screenshot. Apollo Studio supports both JSON
or Raw
formats. For this tutorial select Raw
which downloads the GraphQL schema in the Schema Definition Language (SDL) format.
Clicking Raw
will download a file named star-wars-swapi@current.graphql
.
Step 3: Move the downloaded schema into your project
Download or move the already downloaded star-wars-swapi@current.graphql
file into the directory you created in
Rename the file extension from .graphql
to .graphqls
. Note the s
on the end signifying a GraphQL schema file.
Step 4: Create a GraphQL operation
You'll also need to create a GraphQL operation file because the code generation engine requires both a schema and at least one operation to generate code.
We'll be using the
Copy the query text and create a new file named AllFilmsQuery.graphql
in the directory you created in
query Query {allFilms {films {titledirectorreleaseDatespeciesConnection {species {nameclassificationhomeworld {name}}}}}}
Step 5: Download the CLI
Browse to the list of apollo-ios-cli.tar.gz
Download and unzip this file then move the apollo-ios-cli
binary file into the directory you created in
For more information on the different ways to install the CLI, see the
Step 6: Create a codegen configuration
Run the following command:
./apollo-ios-cli init --schema-namespace StarWarsAPI --module-type swiftPackageManager
The CLI will create a configuration file named apollo-codegen-configuration.json
, pre-filled with default values. The file should look similar to this:
{"schemaNamespace": "StarWarsAPI","input": {"operationSearchPaths": ["**/*.graphql"],"schemaSearchPaths": ["**/*.graphqls"]},"output": {"testMocks": {"none": {}},"schemaTypes": {"path": "./StarWarsAPI","moduleType": {"swiftPackageManager": {}}},"operations": {"inSchemaModule": {}}}}
Step 7: Generate code
Now you are ready to generate some code! Run the following command:
./apollo-ios-cli generate
You should see a new file created at StarWarsAPI/Sources/Operations/Queries/Query.graphql.swift
, that looks similar to this:
And that's it! You can also review all the additional generated files to get a deeper understanding of how code generation works using the Apollo iOS client.