

# Develop REST APIs using OpenAPI in API Gateway
<a name="api-gateway-import-api"></a>

You can use API Gateway to import a REST API from an external definition file into API Gateway. Currently, API Gateway supports [OpenAPI v2.0](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md) and [OpenAPI v3.0](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.1.md) definition files, with exceptions listed in [Amazon API Gateway important notes for REST APIs](api-gateway-known-issues.md#api-gateway-known-issues-rest-apis). You can update an API by overwriting it with a new definition, or you can merge a definition with an existing API. You specify the options by using a `mode` query parameter in the request URL. 

For a tutorial on using the Import API feature from the API Gateway console, see [Tutorial: Create a REST API by importing an example](api-gateway-create-api-from-example.md).

**Topics**
+ [

# Import an edge-optimized API into API Gateway
](import-edge-optimized-api.md)
+ [

# Import a Regional API into API Gateway
](import-export-api-endpoints.md)
+ [

# Import an OpenAPI file to update an existing API definition
](api-gateway-import-api-update.md)
+ [

# Set the OpenAPI `basePath` property
](api-gateway-import-api-basePath.md)
+ [

# AWS variables for OpenAPI import
](import-api-aws-variables.md)
+ [

# Errors and warnings from importing your API into API Gateway
](api-gateway-import-api-errors-warnings.md)
+ [

# Export a REST API from API Gateway
](api-gateway-export-api.md)

# Import an edge-optimized API into API Gateway
<a name="import-edge-optimized-api"></a>

You can import an API's OpenAPI definition file to create a new edge-optimized API by specifying the `EDGE` endpoint type as an additional input, besides the OpenAPI file, to the import operation. You can do so using the API Gateway console, AWS CLI, or an AWS SDK.

For a tutorial on using the Import API feature from the API Gateway console, see [Tutorial: Create a REST API by importing an example](api-gateway-create-api-from-example.md).

**Topics**
+ [

## Import an edge-optimized API using the API Gateway console
](#import-edge-optimized-api-with-console)
+ [

## Import an edge-optimized API using the AWS CLI
](#import-edge-optimized-api-with-awscli)

## Import an edge-optimized API using the API Gateway console
<a name="import-edge-optimized-api-with-console"></a>

To import an edge-optimized API using the API Gateway console, do the following:

1. Sign in to the API Gateway console at [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway).

1. Choose **Create API**.

1. Under **REST API**, choose **Import**.

1.  Copy an API's OpenAPI definition and paste it into the code editor, or choose **Choose file** to load an OpenAPI file from a local drive.

1.  For **API endpoint type**, select **Edge-optimized**.

1.  Choose **Create API** to start importing the OpenAPI definitions.

## Import an edge-optimized API using the AWS CLI
<a name="import-edge-optimized-api-with-awscli"></a>

The following [import-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/import-rest-api.html) command imports an API from an OpenAPI definition file to create a new edge-optimized API:

```
aws apigateway import-rest-api \
    --fail-on-warnings \
    --body 'file://path/to/API_OpenAPI_template.json'
```

or with an explicit specification of the `endpointConfigurationTypes` query string parameter to `EDGE`: 

```
aws apigateway import-rest-api \
    --parameters endpointConfigurationTypes=EDGE \
    --fail-on-warnings \
    --body 'file://path/to/API_OpenAPI_template.json'
```



# Import a Regional API into API Gateway
<a name="import-export-api-endpoints"></a>

When importing an API, you can choose the regional endpoint configuration for the API. You can use the API Gateway console, the AWS CLI, or an AWS SDK.

When you export an API, the API endpoint configuration is not included in the exported API definitions.

For a tutorial on using the Import API feature from the API Gateway console, see [Tutorial: Create a REST API by importing an example](api-gateway-create-api-from-example.md).

**Topics**
+ [

## Import a regional API using the API Gateway console
](#import-regional-api-with-console)
+ [

## Import a regional API using the AWS CLI
](#import-regional-api-with-awscli)

## Import a regional API using the API Gateway console
<a name="import-regional-api-with-console"></a>

To import an API of a regional endpoint using the API Gateway console, do the following:

1. Sign in to the API Gateway console at [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway).

1. Choose **Create API**.

1. Under **REST API**, choose **Import**.

1.  Copy an API's OpenAPI definition and paste it into the code editor, or choose **Choose file** to load an OpenAPI file from a local drive.

1. For **API endpoint type**, select **Regional**.

1.  Choose **Create API** to start importing the OpenAPI definitions.

## Import a regional API using the AWS CLI
<a name="import-regional-api-with-awscli"></a>

The following [import-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/import-rest-api.html) command imports an OpenAPI definition file and sets the endpoint type to Regional:

```
aws apigateway import-rest-api \
    --parameters endpointConfigurationTypes=REGIONAL \
    --fail-on-warnings \
    --body 'file://path/to/API_OpenAPI_template.json'
```

# Import an OpenAPI file to update an existing API definition
<a name="api-gateway-import-api-update"></a>

 You can import API definitions only to update an existing API, without changing its endpoint configuration, as well as stages and stage variables, or references to API keys. 

 The import-to-update operation can occur in two modes: merge or overwrite. 

When an API (`A`) is merged into another (`B`), the resulting API retains the definitions of both `A` and `B` if the two APIs do not share any conflicting definitions. When conflicts arise, the method definitions of the merging API (`A`) overrides the corresponding method definitions of the merged API (`B`). For example, suppose `B` has declared the following methods to return `200` and `206` responses:

```
GET /a
POST /a
```

and `A` declares the following method to return `200` and `400` responses:

```
GET /a
```

When `A` is merged into `B`, the resulting API yields the following methods:

```
GET /a
```

which returns `200` and `400` responses, and 

```
POST /a
```

which returns `200` and `206` responses.

Merging an API is useful when you have decomposed your external API definitions into multiple, smaller parts and only want to apply changes from one of those parts at a time. For example, this might occur if multiple teams are responsible for different parts of an API and have changes available at different rates. In this mode, items from the existing API that aren't specifically defined in the imported definition are left alone. 

When an API (`A`) overwrites another API (`B`), the resulting API takes the definitions of the overwriting API (`A`). Overwriting an API is useful when an external API definition contains the complete definition of an API. In this mode, items from an existing API that aren't specifically defined in the imported definition are deleted. 

 To merge an API, submit a `PUT` request to `https://apigateway.<region>.amazonaws.com/restapis/<restapi_id>?mode=merge`. The `restapi_id` path parameter value specifies the API to which the supplied API definition will be merged. 

 The following code snippet shows an example of the `PUT` request to merge an OpenAPI API definition in JSON, as the payload, with the specified API already in API Gateway. 

```
PUT /restapis/<restapi_id>?mode=merge
Host:apigateway.<region>.amazonaws.com
Content-Type: application/json
Content-Length: ...

An OpenAPI API definition in JSON
```

 The merging update operation takes two complete API definitions and merges them together. For a small and incremental change, you can use the [resource update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateResource.html) operation. 

 To overwrite an API, submit a `PUT` request to `https://apigateway.<region>.amazonaws.com/restapis/<restapi_id>?mode=overwrite`. The `restapi_id` path parameter specifies the API that will be overwritten with the supplied API definitions. 

 The following code snippet shows an example of an overwriting request with the payload of a JSON-formatted OpenAPI definition: 

```
PUT /restapis/<restapi_id>?mode=overwrite
Host:apigateway.<region>.amazonaws.com
Content-Type: application/json
Content-Length: ...

An OpenAPI API definition in JSON
```

 When the `mode` query parameter isn't specified, merge is assumed.

**Note**  
 The `PUT` operations are idempotent, but not atomic. That means if a system error occurs part way through processing, the API can end up in a bad state. However, repeating the operation successfully puts the API into the same final state as if the first operation had succeeded. 

# Set the OpenAPI `basePath` property
<a name="api-gateway-import-api-basePath"></a>

In [OpenAPI 2.0](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md), you can use the `basePath` property to provide one or more path parts that precede each path defined in the `paths` property. Because API Gateway has several ways to express a resource's path, the Import API feature provides the following options for interpreting the `basePath` property during import: ignore, prepend, and split.

In [https://swagger.io/docs/specification/api-host-and-base-path/](https://swagger.io/docs/specification/api-host-and-base-path/), `basePath` is no longer a top-level property. Instead, API Gateway uses a [server variable](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#serverVariableObject) as a convention. The Import API feature provides the same options for interpreting the base path during import. The base path is identified as follows:
+ If the API doesn't contain any `basePath` variables, the Import API feature checks the `server.url` string to see if it contains a path beyond `"/"`. If it does, that path is used as the base path.
+ If the API contains only one `basePath` variable, the Import API feature uses it as the base path, even if it's not referenced in the `server.url`.
+ If the API contains multiple `basePath` variables, the Import API feature uses only the first one as the base path.

## Ignore
<a name="api-gateway-import-api-basePath-ignore"></a>

If the OpenAPI file has a `basePath` value of `/a/b/c` and the `paths` property contains `/e` and `/f`, the following `POST` or `PUT` request: 

```
POST /restapis?mode=import&basepath=ignore
```



```
PUT /restapis/api_id?basepath=ignore
```

 results in the following resources in the API: 
+ `/`
+ `/e`
+ `/f`

 The effect is to treat the `basePath` as if it was not present, and all of the declared API resources are served relative to the host. This can be used, for example, when you have a custom domain name with an API mapping that doesn't include a *Base Path* and a *Stage* value that refers to your production stage. 

**Note**  
 API Gateway automatically creates a root resource for you, even if it isn't explicitly declared in your definition file. 

 When unspecified, `basePath` takes `ignore` by default. 

## Prepend
<a name="api-gateway-import-api-basePath-prepend"></a>

 If the OpenAPI file has a `basePath` value of `/a/b/c` and the `paths` property contains `/e` and `/f`, the following `POST` or `PUT` request: 

```
POST /restapis?mode=import&basepath=prepend
```



```
PUT /restapis/api_id?basepath=prepend
```

 results in the following resources in the API: 
+ `/`
+ `/a`
+ `/a/b`
+ `/a/b/c`
+ `/a/b/c/e`
+ `/a/b/c/f`

 The effect is to treat the `basePath` as specifying additional resources (without methods) and to add them to the declared resource set. This can be used, for example, when different teams are responsible for different parts of an API and the `basePath` could reference the path location for each team's API part. 

**Note**  
 API Gateway automatically creates intermediate resources for you, even if they aren't explicitly declared in your definition. 

## Split
<a name="api-gateway-import-api-basePath-split"></a>

 If the OpenAPI file has a `basePath` value of `/a/b/c` and the `paths` property contains `/e` and `/f`, the following `POST` or `PUT` request: 

```
POST /restapis?mode=import&basepath=split
```



```
PUT /restapis/api_id?basepath=split
```

 results in the following resources in the API: 
+ `/`
+ `/b`
+ `/b/c`
+ `/b/c/e`
+ `/b/c/f`

 The effect is to treat top-most path part, `/a`, as the beginning of each resource's path, and to create additional (no method) resources within the API itself. This could, for example, be used when `a` is a stage name that you want to expose as part of your API. 

# AWS variables for OpenAPI import
<a name="import-api-aws-variables"></a>

You can use the following AWS variables in OpenAPI definitions. API Gateway resolves the variables when the API is imported. To specify a variable, use `${variable-name}`. The following table describes the available AWS variables. 


| Variable name | Description | 
| --- | --- | 
| AWS::AccountId | The AWS account ID that imports the API. For example, 123456789012. | 
| AWS::Partition | The AWS partition in which the API is imported. For standard AWS Regions, the partition is aws. | 
| AWS::Region | The AWS Region in which the API is imported. For example, us-east-2. | 

## AWS variables example
<a name="import-api-aws-variables-example"></a>

The following example uses AWS variables to specify an AWS Lambda function for an integration.

------
#### [ OpenAPI 3.0 ]

```
openapi: "3.0.1"
info:
  title: "tasks-api"
  version: "v1.0"
paths:
  /:
    get:
      summary: List tasks
      description: Returns a list of tasks
      responses:
        200:
          description: "OK"
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Task"
        500:
          description: "Internal Server Error"
          content: {}
      x-amazon-apigateway-integration:
        uri:
          arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:LambdaFunctionName/invocations
        responses:
          default:
            statusCode: "200"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        contentHandling: "CONVERT_TO_TEXT"
        type: "aws_proxy"
components:
  schemas:
    Task:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        description:
          type: string
```

------

# Errors and warnings from importing your API into API Gateway
<a name="api-gateway-import-api-errors-warnings"></a>

When you import your external definition file into API Gateway, API Gateway might generate warnings and errors. The following sections discuss the errors and warnings that might occur during import.

## Errors during import
<a name="api-gateway-import-api-errors"></a>

 During the import, errors can be generated for major issues like an invalid OpenAPI document. Errors are returned as exceptions (for example, `BadRequestException`) in an unsuccessful response. When an error occurs, the new API definition is discarded and no change is made to the existing API. 

## Warnings during import
<a name="api-gateway-import-api-warnings"></a>

 During the import, warnings can be generated for minor issues like a missing model reference. If a warning occurs, the operation will continue if the `failonwarnings=false` query expression is appended to the request URL. Otherwise, the updates will be rolled back. By default, `failonwarnings` is set to `false`. In such cases, warnings are returned as a field in the resulting [RestApi](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html) resource. Otherwise, warnings are returned as a message in the exception. 

# Export a REST API from API Gateway
<a name="api-gateway-export-api"></a>

 Once you created and configured a REST API in API Gateway, using the API Gateway console or otherwise, you can export it to an OpenAPI file using the API Gateway Export API, which is part of the Amazon API Gateway Control Service. To use the API Gateway Export API, you need to sign your API requests. For more information about signing requests, see [Signing AWS API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html) in the *IAM User Guide*. You have options to include the API Gateway integration extensions, as well as the [Postman](https://www.postman.com) extensions, in the exported OpenAPI definition file. 

**Note**  
When exporting the API using the AWS CLI, be sure to include the extensions parameter as shown in the following example, to ensure that the `x-amazon-apigateway-request-validator` extension is included:  

```
aws apigateway get-export --parameters extensions='apigateway' --rest-api-id abcdefg123 --stage-name dev --export-type swagger latestswagger2.json
```

 You cannot export an API if its payloads are not of the `application/json` type. If you try, you will get an error response stating that JSON body models are not found. 

## Request to export a REST API
<a name="api-gateway-export-api-request"></a>

 With the Export API, you export an existing REST API by submitting a GET request, specifying the to-be-exported API as part of URL paths. The request URL is of the following format: 

------
#### [ OpenAPI 3.0 ]

```
 https://<host>/restapis/<restapi_id>/stages/<stage_name>/exports/oas30
```

------
#### [ OpenAPI 2.0 ]

```
 https://<host>/restapis/<restapi_id>/stages/<stage_name>/exports/swagger
```

------

 You can append the `extensions` query string to specify whether to include API Gateway extensions (with the `integration` value) or Postman extensions (with the `postman` value). 

 In addition, you can set the `Accept` header to `application/json` or `application/yaml` to receive the API definition output in JSON or YAML format, respectively. 

 For more information about submitting GET requests using the API Gateway Export API, see [GetExport](https://docs.aws.amazon.com/apigateway/latest/api/API_GetExport.html). 

**Note**  
 If you define models in your API, they must be for the content type of "application/json" for API Gateway to export the model. Otherwise, API Gateway throws an exception with the "Only found non-JSON body models for ..." error message.   
 Models must contain properties or be defined as a particular JSONSchema type. 

## Download REST API OpenAPI definition in JSON
<a name="api-gateway-export-api-download-swagger-json"></a>

To export and download a REST API in OpenAPI definitions in JSON format:

------
#### [ OpenAPI 3.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30
Host: apigateway.<region>.amazonaws.com
Accept: application/json
```

------
#### [ OpenAPI 2.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger
Host: apigateway.<region>.amazonaws.com
Accept: application/json
```

------

 Here, `<region>` could be, for example, `us-east-1`. For all the regions where API Gateway is available, see [Regions and Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#apigateway_region). 

## Download REST API OpenAPI definition in YAML
<a name="api-gateway-export-api-download-swagger-yaml"></a>

To export and download a REST API in OpenAPI definitions in YAML format:

------
#### [ OpenAPI 3.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
```

------
#### [ OpenAPI 2.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
```

------

## Download REST API OpenAPI definition with Postman extensions in JSON
<a name="api-gateway-export-api-download-swagger-json-with-postman"></a>

To export and download a REST API in OpenAPI definitions with Postman in JSON format:

------
#### [ OpenAPI 3.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30?extensions=postman
Host: apigateway.<region>.amazonaws.com
Accept: application/json
```

------
#### [ OpenAPI 2.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?extensions=postman
Host: apigateway.<region>.amazonaws.com
Accept: application/json
```

------

## Download REST API OpenAPI definition with API Gateway integration in YAML
<a name="api-gateway-export-api-download-swagger-yaml-with-apig"></a>

To export and download a REST API in OpenAPI definitions with API Gateway integration in YAML format:

------
#### [ OpenAPI 3.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/oas30?extensions=integrations
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
```

------
#### [ OpenAPI 2.0 ]

```
GET /restapis/<restapi_id>/stages/<stage_name>/exports/swagger?extensions=integrations
Host: apigateway.<region>.amazonaws.com
Accept: application/yaml
```

------

## Export REST API using the API Gateway console
<a name="api-gateway-export-api-from-console"></a>

After [deploying your REST API to a stage](set-up-deployments.md#create-deployment), you can proceed to export the API in the stage to an OpenAPI file using the API Gateway console.

 In the **Stages** pane in the API Gateway console, choose **Stage actions**, **Export**.

![\[Export REST API using the API Gateway console\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/export-new-console.png)


Specify an **API specification type**, **Format**, and **Extensions** to download your API's OpenAPI definition. 