export const meta = {
  title: `JavaScript, Java, Swift code generation`,
  description: `Amplify's codegen capabilities generates native code for iOS and Android, as well as the generation of types for Flow and TypeScript. It can also generate GraphQL statements(queries, mutations, and subscriptions).`,
};

<MigrationAlert url={"/cli-legacy/graphql-transformer/codegen"}/>

"Codegen" generates native code for Swift (iOS), Java (Android), and JavaScript that represent your GraphQL API's data models. It can also generate GraphQL statements (queries, mutations, and subscriptions) so that you don't have to hand code them.

The design of codegen functionality provides mechanisms to run at different points in your app development lifecycle, including when you create or update an API as well as independently when you want to just update the data fetching requirements of your app but leave your API alone. It additionally allows you to work in a team where the schema is updated or managed by another person. Finally, you can also include the codegen in your build process so that it runs automatically (such as from in Xcode).

## Create API then automatically generate code

```bash
amplify init
amplify add api (select GraphQL)
amplify push
```

You’ll see questions as before, but now it will also automatically ask you if you want to generate GraphQL statements and do codegen. It will also respect the `./app/src/main` directory for Android projects. After the AppSync deployment finishes the Swift file will be automatically generated (Android you’ll need to kick off a [Gradle Build step](#androiduse)) and you can begin using in your app immediately.

When you deploy your GraphQL API to the cloud, you are prompted to configure codegen. When a project is configured to generate code with codegen, it stores all the configuration `.graphqlconfig.yml` file in the root folder of your project. To make changes to the configuration, use `amplify configure codegen`.

## Modify GraphQL schema, push, then automatically generate code

During development, you might wish to update your GraphQL schema and generated code as part of an iterative dev/test cycle. Modify & save your schema in `amplify/backend/api/<apiname>/schema.graphql` then run:

```bash
amplify push
```

Each time you will be prompted to update the code in your API and also ask you if you want to run codegen again as well, including regeneration of the GraphQL statements from the new schema.

## No API changes, just update GraphQL statements & generate code

One of the benefits of GraphQL is the client can define it's data fetching requirements independently of the API. Amplify codegen supports this by allowing you to modify the selection set (e.g. add/remove fields inside the curly braces) for the GraphQL statements and running type generation again. This gives you fine-grained control over the network requests that your application is making. Modify your GraphQL statements (default in the `./graphql` folder unless you changed it) then save the files and run:

```bash
amplify codegen types
```

A new updated Swift file will be created (or run Gradle Build on Android for the same). You can then use the updates in your application code.

## Shared schema, modified elsewhere (e.g. console or team workflows)

Suppose you are working in a team and the schema is updated either from the AWS AppSync console or on another system. Your types are now out of date because your GraphQL statement was generated off an outdated schema. The easiest way to resolve this is to regenerate your GraphQL statements, update them if necessary, and then generate your types again. Modify the schema in the console or on a separate system, then run:

```bash
amplify codegen statements
amplify codegen types
```

You should have newly generated GraphQL statements and Swift code that matches the schema updates. If you ran the second command your types will be updated as well. Alternatively, if you run `amplify codegen` alone it will perform both of these actions.

## Introspection Schema outside of an initialized project

If you would like to generate statements and types without initializing an amplify project, you can do so by providing your introspection schema named `schema.json` in your project directory and adding codegen from the same directory. To download your introspection schema from an AppSync api, in the AppSync console go to the schema editor and under "Export schema" choose `schema.json`.

```bash
amplify add codegen
```

Once codegen has been added you can update your introspection schema, then generate statements and types again without re-entering your project information.

```bash
amplify codegen
```

You can update your project and codegen configuration if required.

```bash
amplify configure codegen
amplify codegen
```

When generating types, codegen uses GraphQL statements as input. It will generate only the types that are being used in the GraphQL statements.

## Codegen commands

### amplify add codegen

```bash
amplify add codegen
```

The `amplify add codegen` allows you to add AppSync API created using the AWS console. If you have your API is in a different region then that of your current region, the command asks you to choose the region. If you are adding codegen outside of an initialized amplify project, provide your introspection schema named `schema.json` in the same directory that you make the add codegen call from.
__Note__: If you use the --apiId flag to add an externally created AppSync API, such as one created in the AWS console, you will not be able to manage this API from the Amplify CLI with commands such as amplify api update when performing schema updates. You cannot add an external AppSync API when outside of an initialized project.

### amplify configure codegen

```bash
amplify configure codegen
```

The `amplify configure codegen` command allows you to update the codegen configuration after it is added to your project. When outside of an initialized project, you can use this to update your project configuration as well as the codegen configuration.

### amplify codegen statements

```bash
amplify codegen statements [--nodownload] [--maxDepth <int>]
```

The `amplify codegen statements` command  generates GraphQL statements(queries, mutation and subscription) based on your GraphQL schema. This command downloads introspection schema every time it is run, but it can be forced to use previously downloaded introspection schema by passing `--nodownload` flag.

### amplify codegen types

```bash
amplify codegen types
```

The `amplify codegen types [--nodownload]` command generates GraphQL `types` for Flow and typescript and Swift class in an iOS project. This command downloads introspection schema every time it is run, but it can be forced to use previously downloaded introspection schema by passing `--nodownload` flag.

### amplify codegen

```bash
amplify codegen [--maxDepth <int>]
```

The `amplify codegen [--nodownload]` generates GraphQL `statements` and `types`. This command downloads introspection schema every time it is run but it can be forced to use previously downloaded introspection schema by passing `--nodownload` flag. If you are running codegen outside of an initialized amplify project, the introspection schema named `schema.json` must be in the same directory that you run amplify codegen from. This command will not download the introspection schema when outside of an amplify project - it will only use the introspection schema provided.

## Statement depth

In the below schema there are connections between `Comment` -> `Post` -> `Blog` -> `Post` -> `Comments`. When generating statements codegen has a default limit of 2 for depth traversal. But if you need to go deeper than 2 levels you can change the `maxDepth` parameter either when setting up your codegen or by passing  `--maxDepth` parameter to `codegen`

```graphql
type Blog @model {
  id: ID!
  name: String!
  posts: [Post] @hasMany
}
type Post @model {
  id: ID!
  title: String!
  blog: Blog @belongsTo
  comments: [Comment] @hasMany
}
type Comment @model {
  id: ID!
  content: String
  post: Post @belongsTo
}
```

```graphql
query GetComment($id: ID!) {
  getComment(id: $id) { # depth level 1
    id
    content
    post { # depth level 2
      id
      title
      blog { # depth level 3
        id
        name
        posts { # depth level 4
          items { # depth level 5
            id
            title
          }
          nextToken
        }
      }
      comments { # depth level 3
        items { # depth level 4
          id
          content
          post { # depth level 5
            id
            title
          }
        }
        nextToken
      }
    }
  }
}
```
