

# Distribute your REST APIs to clients in API Gateway
<a name="rest-api-distribute"></a>

This section provides details about distributing your API Gateway APIs to your customers. Distributing your API includes generating SDKs for your customers to download and integrate with their client applications, documenting your API so customers know how to call it from their client applications, and making your API available as part of product offerings.



**Topics**
+ [Usage plans and API keys for REST APIs in API Gateway](api-gateway-api-usage-plans.md)
+ [Documentation for REST APIs in API Gateway](api-gateway-documenting-api.md)
+ [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md)
+ [Sell your API Gateway APIs through AWS Marketplace](sell-api-as-saas-on-aws-marketplace.md)

# Usage plans and API keys for REST APIs in API Gateway
<a name="api-gateway-api-usage-plans"></a>

After you create, test, and deploy your APIs, you can use API Gateway usage plans to make them available as product offerings for your customers. You can configure usage plans and API keys to allow customers to access selected APIs, and begin throttling requests to those APIs based on defined limits and quotas. These can be set at the API, or API method level.

## What are usage plans and API keys?
<a name="api-gateway-api-usage-plans-overview"></a>

A *usage plan* specifies who can access one or more deployed API stages and methods—and optionally sets the target request rate to start throttling requests. The plan uses API keys to identify API clients and who can access the associated API stages for each key. 

*API keys* are alphanumeric string values that you distribute to application developer customers to grant access to your API. You can use API keys together with [Lambda authorizers](apigateway-use-lambda-authorizer.md), [IAM roles](permissions.md), or [Amazon Cognito](apigateway-integrate-with-cognito.md) to control access to your APIs. API Gateway can generate API keys on your behalf, or you can import them from a [CSV file](api-key-file-format.md). You can generate an API key in API Gateway, or import it into API Gateway from an external source. For more information, see [Set up API keys for REST APIs in API Gateway](api-gateway-setup-api-keys.md). 

An API key has a name and a value. (The terms "API key" and "API key value" are often used interchangeably.) The name cannot exceed 1024 characters. The value is an alphanumeric string between 20 and 128 characters, for example, `apikey1234abcdefghij0123456789`.

**Important**  
API key values must be unique. If you try to create two API keys with different names and the same value, API Gateway considers them to be the same API key.  
An API key can be associated with more than one usage plan. A usage plan can be associated with more than one stage. However, a given API key can only be associated with one usage plan for each stage of your API.

A *throttling limit* sets the target point at which request throttling should start. This can be set at the API or API method level.

A *quota limit* sets the target maximum number of requests with a given API key that can be submitted within a specified time interval. You can configure individual API methods to require API key authorization based on usage plan configuration.

Throttling and quota limits apply to requests for individual API keys that are aggregated across all API stages within a usage plan.

**Note**  
Usage plan throttling and quotas are not hard limits, and are applied on a best-effort basis. In some cases, clients can exceed the quotas that you set. Don’t rely on usage plan quotas or throttling to control costs or block access to an API. Consider using [AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) to monitor costs and [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) to manage API requests.

## Best practices for API keys and usage plans
<a name="apigateway-usage-plans-best-practices"></a>

The following are suggested best practices to follow when using API keys and usage plans.

**Important**  
Don't use API keys for authentication or authorization to control access to your APIs. If you have multiple APIs in a usage plan, a user with a valid API key for one API in that usage plan can access *all* APIs in that usage plan. Instead, to control access to your API, use an IAM role, a [Lambda authorizer](apigateway-use-lambda-authorizer.md), or an [Amazon Cognito user pool](apigateway-integrate-with-cognito.md).
Use API keys that API Gateway generates. API keys shouldn't include confidential information; clients typically transmit them in headers that can be logged.
+ If you're using a developer portal to publish your APIs, note that all your APIs in a given usage plan can be subscribed to by customers, even if you haven't made them visible to your customers.
+ In some cases, clients can exceed the quotas that you set. Don’t rely on usage plans to control costs. Consider using [AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) to monitor costs and [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) to manage API requests.
+ After you add an API key to a usage plan, the update operation might take a few minutes to complete.

# Choose an API key source in API Gateway
<a name="api-gateway-api-key-source"></a>

When you associate a usage plan with an API and enable API keys on API methods, every incoming request to the API must contain an [API key](api-gateway-basic-concept.md#apigateway-definition-api-key). API Gateway reads the key and compares it against the keys in the usage plan. If there is a match, API Gateway throttles the requests based on the plan's request limit and quota. Otherwise, it throws an `InvalidKeyParameter` exception. As a result, the caller receives a `403 Forbidden` response.

Your API Gateway API can receive API keys from one of two sources:

**`HEADER`**  
You distribute API keys to your customers and require them to pass the API key as the `X-API-Key` header of each incoming request. 

**`AUTHORIZER`**  
You have a Lambda authorizer return the API key as part of the authorization response. For more information on the authorization response, see [Output from an API Gateway Lambda authorizer](api-gateway-lambda-authorizer-output.md).

**Note**  
For best practices to consider, see [Best practices for API keys and usage plans](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices).

The following procedure shows how to choose an API key source for an API.

------
#### [ AWS Management Console ]

**To choose an API key source for an API**

1. Sign in to the API Gateway console.

1. Choose an existing API or create a new one.

1. In the main navigation pane, choose **API settings**. 

1. In the **API details** section, choose **Edit**. 

1.  Under **API key source**, select `Header` or `Authorizer` from the dropdown list.

1. Choose **Save changes**.

------
#### [ AWS CLI ]

The following [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) command updates an API to set the API key source to `AUTHORIZER`:

```
aws apigateway update-rest-api --rest-api-id 1234123412 --patch-operations op=replace,path=/apiKeySource,value=AUTHORIZER
```

To have the client submit an API key, set the `value` to `HEADER` in the previous command.

------
#### [ REST API ]

To choose an API key source for an API by using the API Gateway REST API, call [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html) as follows:

```
PATCH /restapis/fugvjdxtri/ HTTP/1.1
Content-Type: application/json
Host: apigateway.us-east-1.amazonaws.com
X-Amz-Date: 20160603T205348Z
Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160603/us-east-1/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature={sig4_hash}

{
  "patchOperations" : [
    {
        "op" : "replace",
        "path" : "/apiKeySource",
        "value" : "HEADER"
    }
  ]
}
```

To have an authorizer return an API key, set the `value` to `AUTHORIZER` in the previous `patchOperations` input.

------

# API Gateway API key file format
<a name="api-key-file-format"></a>

API Gateway can import API keys from external files of a comma-separated value (CSV) format, and then associate the imported keys with one or more usage plans. The imported file must contain the `Name` and `Key` columns. The column header names aren't case sensitive, and columns can be in any order, as shown in the following example: 

```
Key,name
apikey1234abcdefghij0123456789,MyFirstApiKey
```

A `Key` value must be between 20 and 128 characters. A `Name` value cannot exceed 1024 characters. 

An API key file can also have the `Description`, `Enabled`, or `UsagePlanIds` column, as shown in the following example: 

```
Name,key,description,Enabled,usageplanIds
MyFirstApiKey,apikey1234abcdefghij0123456789,An imported key,TRUE,c7y23b
```

When a key is associated with more than one usage plan, the `UsagePlanIds` value is a comma-separated string of the usage plan IDs, enclosed with a pair of double or single quotes, as shown in the following example:

```
Enabled,Name,key,UsageplanIds
true,MyFirstApiKey,apikey1234abcdefghij0123456789,"c7y23b,glvrsr"
```

Unrecognized columns are permitted, but are ignored. The default value is an empty string or a `true` Boolean value. 

The same API key can be imported multiple times, with the most recent version overwriting the previous one. Two API keys are identical if they have the same `key` value. 

**Note**  
For best practices to consider, see [Best practices for API keys and usage plans](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices).

# Set up API keys for REST APIs in API Gateway
<a name="api-gateway-setup-api-keys"></a>

To set up API keys, do the following:
+ Configure API methods to require an API key.
+ Create or import an API key for the API in a Region.

Before setting up API keys, you must have created an API and deployed it to a stage. After you create an API key value, it cannot be changed.

For instructions on how to create and deploy an API by using the API Gateway console, see [Develop REST APIs in API Gateway](rest-api-develop.md) and [Deploy REST APIs in API Gateway](how-to-deploy-api.md), respectively.

After you create an API key, you must associate it with a usage plan. For more information, see [Set up usage plans for REST APIs in API Gateway](api-gateway-create-usage-plans.md).

**Note**  
For best practices to consider, see [Best practices for API keys and usage plans](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices).

**Topics**
+ [Require an API key on a method](#api-gateway-usage-plan-configure-apikey-on-method)
+ [Create an API key](#api-gateway-usage-plan-create-apikey)
+ [Import API keys](#api-gateway-usage-pan-import-apikey)

## Require an API key on a method
<a name="api-gateway-usage-plan-configure-apikey-on-method"></a>

The following procedure describes how to configure an API method to require an API key.

------
#### [ AWS Management Console ]

**To configure an API method to require an API key**

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

1. Choose a REST API.

1. In the API Gateway main navigation pane, choose **Resources**.

1. Under **Resources**, create a new method or choose an existing one.

1. On the **Method request** tab, under **Method request settings**, choose **Edit**.  
![\[Add an API key to a method\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/api-gateway-new-console-add-key-to-method.png)

1. Select **API key required**.

1. Choose **Save**.

1. Deploy or redeploy the API for the requirement to take effect.

If the **API key required** option is set to `false` and you don't execute the previous steps, any API key that's associated with an API stage isn't used for the method.

------
#### [ AWS CLI ]

The following [put-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-method.html) command creates a `PUT` method that requires an API key:

```
aws apigateway put-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method PUT \
    --authorization-type "NONE" \
    --api-key-required
```

The following [update-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-method.html) command updates an existing method to require an API key:

```
aws apigateway update-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method PUT \
    --patch-operations op="replace",path="/apiKeyRequired",value="true"
```

------
#### [ REST API ]

To require an API key on a method, do one of the following:
+ Call [https://docs.aws.amazon.com/apigateway/latest/api/API_PutMethod.html](https://docs.aws.amazon.com/apigateway/latest/api/API_PutMethod.html) to create a method. Set `apiKeyRequired` to `true` in the request payload.
+ Call [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateMethod.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateMethod.html) to set `apiKeyRequired` to `true`.

------

## Create an API key
<a name="api-gateway-usage-plan-create-apikey"></a>

The following procedure shows how to create an API key. If you want to import your API key, skip this step.

------
#### [ AWS Management Console ]

**To create an API key**

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

1. Choose a REST API.

1. In the API Gateway main navigation pane, choose **API keys**.

1. Choose **Create API key**.  
![\[Create API keys for usage plans\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-choose-create-api-key-from-actions-menu.png)

1. For **Name**, enter a name.

1. (Optional) For **Description**, enter a description.

1. For **API key**, choose **Auto generate** to have API Gateway generate the key value, or choose **Custom** to create your own key value.

1. Choose **Save**.

------
#### [ AWS CLI ]

The following [create-api-key](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-api-key.html) command creates an API key:

```
 aws apigateway create-api-key \
    --name 'Dev API key' \
    --description 'API key for Devs' \
    --enabled
```

------
#### [ REST API ]

Call [https://docs.aws.amazon.com/apigateway/latest/api/API_CreateApiKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateApiKey.html) to create an API key.

------

## Import API keys
<a name="api-gateway-usage-pan-import-apikey"></a>

The following procedure describes how to import API keys. If you already created an API key, skip this step.

------
#### [ AWS Management Console ]

**To import API keys**

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

1. Choose a REST API.

1. In the main navigation pane, choose **API keys**.

1. Choose the **Actions** dropdown menu, and then choose **Import API keys**. 

1. To load a comma-separated key file, choose **Choose file**. You can also enter the keys in the text editor. For information about the file format, see [API Gateway API key file format](api-key-file-format.md).

1. Choose **Fail on warnings** to stop the import when there's an error, or choose **Ignore warnings** to continue to import valid key entries when there's an warning.

1. Choose **Import** to import your API keys.

------
#### [ AWS CLI ]

The following [import-api-keys](https://docs.aws.amazon.com/cli/latest/reference/apigateway/import-api-keys.html) command imports an API key:

```
aws apigateway import-api-key \
    a--body fileb://keys.csv \
    --format csv
```

------
#### [ REST API ]

Call [https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html](https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html) to import an API key from a file. For the file format, see [API Gateway API key file format](api-key-file-format.md).

------

You cannot change the value of the new API key. After you create your API, you configure a usage plan. For more information, see [Set up usage plans for REST APIs in API Gateway](api-gateway-create-usage-plans.md).

# Set up usage plans for REST APIs in API Gateway
<a name="api-gateway-create-usage-plans"></a>

Before you create a usage plan, make sure that you've set up the your API keys. For more information, see [Set up API keys for REST APIs in API Gateway](api-gateway-setup-api-keys.md).

**Topics**
+ [Migrate your API to default usage plans (if needed)](#api-gateway-usage-plan-migrate-to-default)
+ [Create a usage plan](#api-gateway-usage-plan-create)
+ [Add a stage to a usage plan](#api-gateway-usage-plan-add-stage)
+ [Add an API key to a usage plan](#api-gateway-usage-plan-add-key)

## Migrate your API to default usage plans (if needed)
<a name="api-gateway-usage-plan-migrate-to-default"></a>

If you started to use API Gateway *after* the usage plans feature was rolled out on August 11, 2016, you will automatically have usage plans enabled for you in all supported Regions.

If you started to use API Gateway before that date, you might need to migrate to default usage plans. You'll be prompted with the **Enable Usage Plans** option before using usage plans for the first time in the selected Region. When you enable this option, you have default usage plans created for every unique API stage that's associated with existing API keys. In the default usage plan, no throttle or quota limits are set initially, and the associations between the API keys and API stages are copied to the usage plans. The API behaves the same as before. However, you must use the [https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlan.html) `apiStages` property to associate specified API stage values (`apiId` and `stage`) with included API keys (via [https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlanKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlanKey.html)), instead of using the [ApiKey](https://docs.aws.amazon.com/apigateway/latest/api/API_ApiKey.html) `stageKeys` property.

To check whether you've already migrated to default usage plans, use the [https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-account.html](https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-account.html) CLI command. In the command output, the `features` list includes an entry of `"UsagePlans"` when usage plans are enabled.

You can also migrate your APIs to default usage plans by using the AWS CLI as follows:

**To migrate to default usage plans using the AWS CLI**

1. Call this CLI command: [https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-account.html](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-account.html).

1. For the `cli-input-json` parameter, use the following JSON:

   ```
   [
       {
           "op": "add",
           "path": "/features",
           "value": "UsagePlans"
       }
   ]
   ```

## Create a usage plan
<a name="api-gateway-usage-plan-create"></a>

The following procedure describes how to create a usage plan.

------
#### [ AWS Management Console ]

**To create a usage plan**

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

1. In the API Gateway main navigation pane, choose **Usage plans**, and then choose **Create usage plan**.  
![\[API usage plan entities\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-create-setup.png)

1. For **Name**, enter a name.

1.  (Optional) For **Description**, enter a description. 

1. By default, usage plans enable throttling. Enter a **Rate** and a **Burst** for your usage plan. Choose **Throttling** to turn off throttling. 

1. By default, usage plans enable a quota for a time period. For **Requests**, enter the total number of requests that a user can make in the time period of your usage plan. Choose **Quota** to turn off the quota.

1. Choose **Create usage plan**.

------
#### [ AWS CLI ]

The following [create-usage-plan](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-usage-plan.html) command creates a usage plan that resets at the beginning of the month:

```
aws apigateway create-usage-plan \
    --name "New Usage Plan" \
    --description "A new usage plan" \
    --throttle burstLimit=10,rateLimit=5 \
    --quota limit=500,offset=0,period=MONTH
```

------
#### [ REST API ]

Call [https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlan.html) to create a usage plan.

------

## Add a stage to a usage plan
<a name="api-gateway-usage-plan-add-stage"></a>

The following procedure describes how to add a stage to a usage plan.

------
#### [ AWS Management Console ]

**To add a stage to a usage plan**

1. Select your usage plan.

1.  Under the **Associated stages** tab, choose **Add stage**.  
![\[Add an API stage to a usage plan.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-create-add-stage.png)

1.  For **API**, select an API. 

1.  For **Stage**, select a stage. 

1. (Optional) To turn on method-level throttling, do the following:

   1. Choose **Method-level throttling**, and then choose **Add method**.

   1. For **Resource**, select a resource from your API. 

   1. For **Method**, select a method from your API. 

   1.  Enter a **Rate** and a **Burst** for your usage plan. 

1. Choose **Add to usage plan**.

------
#### [ AWS CLI ]

The following [update-usage-plan](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-usage-plan.html) command adds the `Prod` stage of an API to a usage plan:

```
aws apigateway update-usage-plan \
    --usage-plan-id abc123 \
    --patch-operations op="add",path="/apiStages",value="a1b1c2:Prod"
```

------
#### [ REST API ]

Call [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html) to update a usage plan.

------

## Add an API key to a usage plan
<a name="api-gateway-usage-plan-add-key"></a>

The following procedure shows how to add an API key to a usage plan.

------
#### [ AWS Management Console ]

**To add a key to a usage plan**

1. Under the **Associated API keys** tab, choose **Add API key**.   
![\[API usage plan entities\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/api-gateway-new-console-usage-plan-keys-create-add-key.png)

1. 

   1.  To associate an existing key to your usage plan, select **Add existing key**, and then select your existing key from the dropdown menu.

   1. To create a new API key, select **Create and add new key**, and then create a new key. For more information on how to create a new key, see [Create an API key](api-gateway-setup-api-keys.md#api-gateway-usage-plan-create-apikey).

1. Choose **Add API key**.

------
#### [ AWS CLI ]

The following [create-usage-plan-key](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-usage-plan-key.html) command associates an existing API key with a usage plan:

```
aws apigateway create-usage-plan-key \
    --usage-plan-id a1b2c3 \
    --key-type "API_KEY" \
    --key-id aaa111bbb
```

------
#### [ REST API ]

Call [https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlanKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateUsagePlanKey.html) to associate an existing API key with a usage plan.

You can also directly associate your APIs keys with a usage plan when you import them. Call [https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html](https://docs.aws.amazon.com/apigateway/latest/api/API_ImportApiKeys.html) to add one or more API keys directly to the specified usage plan. The request payload should contain API key values, the associated usage plan identifier, the Boolean flags to indicate that the keys are enabled for the usage plan, and, possibly, the API key names and descriptions. 

The following example of the `apikey:import` request adds three API keys (as identified by `key`, `name`, and `description`) to one usage plan (as identified by `usageplanIds`): 

```
POST /apikeys?mode=import&format=csv&failonwarnings=fase HTTP/1.1
Host: apigateway.us-east-1.amazonaws.com
Content-Type: text/csv
Authorization: ...

key,name, description, enabled, usageplanIds
abcdef1234ghijklmnop8901234567, importedKey_1, firstone,  tRuE, n371pt 
abcdef1234ghijklmnop0123456789, importedKey_2, secondone, TRUE, n371pt
abcdef1234ghijklmnop9012345678, importedKey_3,          , true, n371pt
```

As a result, three `UsagePlanKey` resources are created and added to the `UsagePlan`.

You can also add API keys to more than one usage plan this way. To do this, change each `usageplanIds` column value to a comma-separated string that contains the selected usage plan identifiers, and is enclosed within a pair of quotes (`"n371pt,m282qs"` or `'n371pt,m282qs'`).

------

**Note**  
An API key can be associated with more than one usage plan. A usage plan can be associated with more than one stage. However, a given API key can only be associated with one usage plan for each stage of your API.

# Maintain a usage plan for REST APIs in API Gateway
<a name="api-gateway-usage-plan-manage-usage"></a>

Maintaining a usage plan involves monitoring the used and remaining quotas over a given time period and, if needed, extending the remaining quotas by a specified amount. The following procedures describe how to monitor quotas.

------
#### [ AWS Management Console ]

**To monitor used and remaining quotas**

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

1. In the API Gateway main navigation pane, choose **Usage plans**.

1. Select a usage plan.

1. Choose the **Associated API keys** tab to see the number of request remaining for the time period for each key.

1. (Optional) Choose **Export usage data**, and then choose a **From** date and a **To** date. Then choose **JSON** or **CSV** for the exported data format, and then choose **Export**.

   The following example shows an exported file. 

   ```
   {
       "px1KW6...qBazOJH": [
         [
           0,
           5000
         ],
         [
           0,
           5000
         ],
         [
           0,
           10
         ]
       ]
     }
   ```

   The usage data in the example shows the daily usage data for an API client, as identified by the API key (`px1KW6...qBazOJH`), between August 1, 2016 and August 3, 2016. Each daily usage data shows used and remaining quotas. In this example, the subscriber hasn't used any allotted quotas yet, and the API owner or administrator has reduced the remaining quota from 5000 to 10 on the third day.

The following procedures describe how to modify quotas.

**To extend the remaining quotas**

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

1. In the API Gateway main navigation pane, choose **Usage plans**.

1. Select a usage plan.

1. Choose the **Associated API keys** tab to see the number of request remaining for the time period for each key.

1. Select an API key, and then choose **Grant usage extension**.

1. Enter a number for the **Remaining requests** quota. You can increase the renaming requests or decrease the remaining requests for the time period of your usage plan. 

1. Choose **Update quota**.

------
#### [ AWS CLI ]

The following [update-usage-plan](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-usage-plan.html) examples add, remove, or modify the method-level throttling settings in a usage plan.

**Note**  
Be sure to change `us-east-1` to the appropriate Region value for your API.

To add or replace a rate limit for throttling an individual resource and method:

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch-operations op="replace",path="/apiStages/apiId:stage/throttle/resourcePath/httpMethod/rateLimit",value="0.1"
```

To add or replace a burst limit for throttling an individual resource and method:

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch-operations op="replace",path="/apiStages/apiId:stage/throttle/resourcePath/httpMethod/burstLimit",value="1"
```

To remove the method-level throttling settings for an individual resource and method:

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch-operations op="remove",path="/apiStages/apiId:stage/throttle/resourcePath/httpMethod",value=""
```

To remove all method-level throttling settings for an API:

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch-operations op="remove",path="/apiStages/apiId:stage/throttle ",value=""
```

Here is an example using the Pet Store sample API:

```
aws apigateway --region us-east-1 update-usage-plan --usage-plan-id planId --patch-operations op="replace",path="/apiStages/apiId:stage/throttle",value='"{\"/pets/GET\":{\"rateLimit\":1.0,\"burstLimit\":1},\"//GET\":{\"rateLimit\":1.0,\"burstLimit\":1}}"'
```

------
#### [ REST API ]

Call [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateUsagePlan.html) to maintain a usage plan.

------

# Create and configure API keys and usage plans with CloudFormation
<a name="api-key-usage-plan-cfn"></a>

 You can use CloudFormation to require API keys on API methods and create a usage plan for an API. The example CloudFormation template does the following:
+ Creates an API Gateway API with `GET` and `POST` methods.
+ Requires an API key for the `GET` and `POST` methods. This API receives keys from the `X-API-KEY` header of each incoming request. 
+ Creates an API key.
+ Creates a usage plan to specify a monthly quota of 1,000 request each month, a throttling rate limit of 100 request each second, and a throttling burst limit of 200 request each second. 
+ Specifies a method-level throttling rate limit of 50 requests each second and a method-level throttling burst limit of 100 requests per second for the `GET` method.
+ Associates the API stage and API key with the usage plan. 

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  StageName:
    Type: String
    Default: v1
    Description: Name of API stage.
  KeyName:
    Type: String
    Default: MyKeyName
    Description: Name of an API key
Resources:
  Api:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: keys-api
      ApiKeySourceType: HEADER
  PetsResource:
    Type: 'AWS::ApiGateway::Resource'
    Properties:
      RestApiId: !Ref Api
      ParentId: !GetAtt Api.RootResourceId
      PathPart: 'pets'
  PetsMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: GET
      ApiKeyRequired: true
      AuthorizationType: NONE
      Integration:
        Type: HTTP_PROXY
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
  PetsMethodPost:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref PetsResource
      HttpMethod: POST
      ApiKeyRequired: true
      AuthorizationType: NONE
      Integration:
        Type: HTTP_PROXY
        IntegrationHttpMethod: GET
        Uri: http://petstore-demo-endpoint.execute-api.com/petstore/pets/
  ApiDeployment:
    Type: 'AWS::ApiGateway::Deployment'
    DependsOn:
      - PetsMethodGet
    Properties:
      RestApiId: !Ref Api
      StageName: !Sub '${StageName}'
  UsagePlan:
    Type: AWS::ApiGateway::UsagePlan
    DependsOn:
      - ApiDeployment
    Properties:
      Description: Example usage plan with a monthly quota of 1000 calls and method-level throttling for /pets GET 
      ApiStages:
        - ApiId: !Ref Api
          Stage: !Sub '${StageName}'
          Throttle:
            "/pets/GET": 
              RateLimit: 50.0
              BurstLimit: 100
      Quota:
        Limit: 1000
        Period: MONTH
      Throttle:
        RateLimit: 100.0
        BurstLimit: 200
      UsagePlanName: "My Usage Plan"
  ApiKey:
    Type: AWS::ApiGateway::ApiKey
    Properties: 
      Description: API Key
      Name: !Sub '${KeyName}'
      Enabled: True
  UsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref UsagePlan
Outputs:
  ApiRootUrl:
    Description: Root Url of the API
    Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com/${StageName}'
```

# Configure a method to use API keys with an OpenAPI definition
<a name="api-key-usage-plan-oas"></a>

You can use an OpenAPI definition to require API keys on a method.

For each method, create a security requirement object to require an API key to invoke that method. Then, define `api_key` in the security definition. After you create your API, add the new API stage to your usage plan.

The following example creates an API and requires an API key for the `POST` and `GET` methods:

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

```
{
  "swagger" : "2.0",
  "info" : {
    "version" : "2024-03-14T20:20:12Z",
    "title" : "keys-api"
  },
  "basePath" : "/v1",
  "schemes" : [ "https" ],
  "paths" : {
    "/pets" : {
      "get" : {
        "responses" : { },
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "type" : "http_proxy",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match"
        }
      },
      "post" : {
        "responses" : { },
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "type" : "http_proxy",
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match"
        }
      }
    }
  },
  "securityDefinitions" : {
    "api_key" : {
      "type" : "apiKey",
      "name" : "x-api-key",
      "in" : "header"
    }
  }
}
```

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

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "keys-api",
    "version" : "2024-03-14T20:20:12Z"
  },
  "servers" : [ {
    "url" : "{basePath}",
    "variables" : {
      "basePath" : {
        "default" : "v1"
      }
    }
  } ],
  "paths" : {
    "/pets" : {
      "get" : {
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match",
          "type" : "http_proxy"
        }
      },
      "post" : {
        "security" : [ {
          "api_key" : [ ]
        } ],
        "x-amazon-apigateway-integration" : {
          "httpMethod" : "GET",
          "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets/",
          "passthroughBehavior" : "when_no_match",
          "type" : "http_proxy"
        }
      }
    }
  },
  "components" : {
    "securitySchemes" : {
      "api_key" : {
        "type" : "apiKey",
        "name" : "x-api-key",
        "in" : "header"
      }
    }
  }
}
```

------

# Test usage plans for REST APIs in API Gateway
<a name="api-gateway-usage-plan-test-with-postman"></a>

As an example, let's use the PetStore API, which was created in [Tutorial: Create a REST API by importing an example](api-gateway-create-api-from-example.md). Assume that the API is configured to use an API key of `Hiorr45VR...c4GJc`. The following steps describe how to test a usage plan.

**To test your usage plan**
+ Make a `GET` request on the Pets resource (`/pets`), with the `?type=...&page=...` query parameters, of the API (for example, `xbvxlpijch`) in a usage plan:

  ```
  GET /testStage/pets?type=dog&page=1 HTTP/1.1
  x-api-key: Hiorr45VR...c4GJc
  Content-Type: application/x-www-form-urlencoded
  Host: xbvxlpijch.execute-api.ap-southeast-1.amazonaws.com
  X-Amz-Date: 20160803T001845Z
  Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160803/ap-southeast-1/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-api-key, Signature={sigv4_hash}
  ```
**Note**  
You must submit this request to the `execute-api` component of API Gateway and provide the required API key (for example, `Hiorr45VR...c4GJc`) in the required `x-api-key` header.

  The successful response returns a `200 OK` status code and a payload that contains the requested results from the backend. If you forget to set the `x-api-key` header or set it with an incorrect key, you get a `403 Forbidden` response. However, if you didn't configure the method to require an API key, you will likely get a `200 OK` response whether you set the `x-api-key` header correctly or not, and the throttle and quota limits of the usage plan are bypassed. 

  Occasionally, when an internal error occurs where API Gateway is unable to enforce usage plan throttling limits or quotas for the request, API Gateway serves the request without applying the throttling limits or quotas as specified in the usage plan. But, it logs an error message of `Usage Plan check failed due to an internal error` in CloudWatch. You can ignore such occasional errors. 

# Call a method using an API key
<a name="api-gateway-api-key-call"></a>

Depending on the API key source type you choose, use one of the following procedures to use header-sourced API keys or authorizer-returned API keys in method invocation: 

**To use header-sourced API keys:**

1.  Create an API with desired API methods, and then deploy the API to a stage.

1.  Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan. Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API key value.

1.  Set up API methods to require an API key. 

1.  Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the usage plan to attach the new API stage. 

1. Call the API using the API key. The following example curl command invokes the `GET` method on the `getUsers` resource of the `prod` stage of an API using an API key.

   ```
   curl -H "X-API-Key: abcd1234" 'https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers' 
   ```

The client can now call the API methods while supplying the `x-api-key` header with the chosen API key as the header value. A call might look like the following:

**To use authorizer-sourced API keys:**

1.  Create an API with desired API methods, and then deploy the API to a stage.

1.  Create a new usage plan or choose an existing one. Add the deployed API stage to the usage plan. Attach an API key to the usage plan or choose an existing API key in the plan. Note the chosen API key value.

1.  Create a token-based Lambda authorizer. Include, `usageIdentifierKey:{api-key}` as a root-level property of the authorization response. For instructions on creating a token-based authorizer, see [Example `TOKEN` authorizer Lambda function](apigateway-use-lambda-authorizer.md#api-gateway-lambda-authorizer-token-lambda-function-create).

1.  Set up API methods to require an API key and enable the Lambda authorizer on the methods as well. 

1.  Redeploy the API to the same stage. If you deploy the API to a new stage, make sure to update the usage plan to attach the new API stage. 

The client can now call the API key-required methods without explicitly supplying any API key. The authorizer-returned API key is used automatically.

# Documentation for REST APIs in API Gateway
<a name="api-gateway-documenting-api"></a>

 To help customers understand and use your API, you should document the API. To help you document your API, API Gateway lets you add and update the help content for individual API entities as an integral part of your API development process. API Gateway stores the source content and enables you to archive different versions of the documentation. You can associate a documentation version with an API stage, export a stage-specific documentation snapshot to an external OpenAPI file, and distribute the file as a publication of the documentation. 

To document your API, you can call the [API Gateway REST API](https://docs.aws.amazon.com/apigateway/latest/api/), use one of the [AWS SDKs](https://aws.amazon.com/developer/tools/), use the [AWS CLI](https://docs.aws.amazon.com/cli/latest/reference/apigateway/) for API Gateway, or use the API Gateway console. In addition, you can import or export the documentation parts that are defined in an external OpenAPI file.

To share API documentation with developers, you can use a developer portal. For an example, see [Integrating ReadMe with API Gateway to Keep Your Developer Hub Up to Date](https://aws.amazon.com/blogs/apn/integrating-readme-with-amazon-api-gateway-to-keep-your-developer-hub-up-to-date/) or [How to Streamline API Development on Amazon API Gateway Using SmartBear’s SwaggerHub](https://aws.amazon.com/blogs/apn/how-to-streamline-api-development-on-amazon-api-gateway-using-smartbear-swaggerhub/) on the AWS Partner Network (APN) blog.

**Topics**
+ [Representation of API documentation in API Gateway](api-gateway-documenting-api-content-representation.md)
+ [Document an API using the API Gateway console](api-gateway-documenting-api-quick-start-with-console.md)
+ [Publish API documentation using the API Gateway console](apigateway-documenting-api-with-console.md)
+ [Document an API using the API Gateway REST API](api-gateway-documenting-api-quick-start-with-restapi.md)
+ [Publish API documentation using the API Gateway REST API](api-gateway-documenting-api-quick-start-publishing.md)
+ [Import API documentation](api-gateway-documenting-api-quick-start-import-export.md)
+ [Control access to API documentation in API Gateway](api-gateway-documenting-api-content-provision-and-consumption.md)

# Representation of API documentation in API Gateway
<a name="api-gateway-documenting-api-content-representation"></a>

API Gateway API documentation consists of individual documentation parts associated with specific API entities that include API, resource, method, request, response, message parameters (i.e., path, query, header), as well as authorizers and models. 

In API Gateway, a documentation part is represented by a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource. The API documentation as a whole is represented by the [DocumentationParts](https://docs.aws.amazon.com/apigateway/latest/api/API_GetDocumentationParts.html) collection. 

Documenting an API involves creating `DocumentationPart` instances, adding them to the `DocumentationParts` collection, and maintaining versions of the documentation parts as your API evolves.

**Topics**
+ [Documentation parts](#api-gateway-documenting-api-content-representation-documentation-parts)
+ [Documentation versions](#api-gateway-documenting-api-content-representation-documentation-versions)

## Documentation parts
<a name="api-gateway-documenting-api-content-representation-documentation-parts"></a>

A [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource is a JSON object that stores the documentation content applicable to an individual API entity. This includes any UTF-8 content and all major localization languages for your documentation. Its `properties` field contains the documentation content as a map of key-value pairs. Its `location` property identifies the associated API entity. 

The shape of a content map is determined by you, the API developer. The value of a key-value pair can be a string, number, boolean, object, or array. The shape of the `location` object depends on the targeted entity type. 

The `DocumentationPart` resource supports content inheritance: the documentation content of an API entity is applicable to children of that API entity. For more information about the definition of child entities and content inheritance, see [Inherit Content from an API Entity of More General Specification](#api-gateway-documenting-api-content-inheritance). 

### Location of a documentation part
<a name="api-gateway-documenting-api-content-representation-documentation-parts-target"></a>

The [location](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html#location) property of a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) instance identifies an API entity to which the associated content applies. The API entity can be an API Gateway REST API resource, such as [RestApi](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html), [Resource](https://docs.aws.amazon.com/apigateway/latest/api/API_Resource.html), [Method](https://docs.aws.amazon.com/apigateway/latest/api/API_Method.html), [MethodResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_MethodResponse.html), [Authorizer](https://docs.aws.amazon.com/apigateway/latest/api/API_Authorizer.html), or [Model](https://docs.aws.amazon.com/apigateway/latest/api/API_Model.html). The entity can also be a message parameter, such as a URL path parameter, a query string parameter, a request or response header parameter, a request or response body, or response status code. 

To specify an API entity, set the [type](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html#type) attribute of the `location` object to be one of `API`, `AUTHORIZER`, `MODEL`, `RESOURCE`, `METHOD`, `PATH_PARAMETER`, `QUERY_PARAMETER`, `REQUEST_HEADER`, `REQUEST_BODY`, `RESPONSE`, `RESPONSE_HEADER`, or `RESPONSE_BODY`. 

Depending on the `type` of an API entity, you might specify other `location` attributes, including [method](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html#method), [name](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html#name), [path](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html#path), and [statusCode](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html#statusCode). Not all of these attributes are valid for a given API entity. For example, `type`, `path`, `name`, and `statusCode` are valid attributes of the `RESPONSE` entity; only `type` and `path` are valid location attributes of the `RESOURCE` entity. It is an error to include an invalid field in the `location` of a `DocumentationPart` for a given API entity.

Not all valid `location` fields are required. For example, `type` is both the valid and required `location` field of all API entities. However, `method`, `path`, and `statusCode` are valid but not required attributes for the `RESPONSE` entity. When not explicitly specified, a valid `location` field assumes its default value. The default `path` value is `/`, i.e., the root resource of an API. The default value of `method`, or `statusCode` is `*`, meaning any method, or status code values, respectively.

### Content of a documentation part
<a name="api-gateway-documenting-api-content-representation-documentation-parts-content"></a>

The `properties` value is encoded as a JSON string. The `properties` value contains any information you choose to meet your documentation requirements. For example, the following is a valid content map: 

```
{
  "info": {
    "description": "My first API with Amazon API Gateway."
  },
  "x-custom-info" : "My custom info, recognized by OpenAPI.",
  "my-info" : "My custom info not recognized by OpenAPI."
}
```

Although API Gateway accepts any valid JSON string as the content map, the content attributes are treated as two categories: those that can be recognized by OpenAPI and those that cannot. In the preceding example, `info`, `description`, and `x-custom-info` are recognized by OpenAPI as a standard OpenAPI object, property, or extension. In contrast, `my-info` is not compliant with the OpenAPI specification. API Gateway propagates OpenAPI-compliant content attributes into the API entity definitions from the associated `DocumentationPart` instances. API Gateway does not propagate the non-compliant content attributes into the API entity definitions. 

As another example, here is `DocumentationPart` targeted for a `Resource` entity:

```
{
    "location" : {
        "type" : "RESOURCE",
        "path": "/pets"
    },
    "properties" : {
        "summary" : "The /pets resource represents a collection of pets in PetStore.",
        "description": "... a child resource under the root...",
    }
}
```

Here, both `type` and `path` are valid fields to identify the target of the `RESOURCE` type. For the root resource (`/`), you can omit the `path` field.

```
{
    "location" : {
        "type" : "RESOURCE"
    },
    "properties" : {
        "description" : "The root resource with the default path specification."
    }
}
```

This is the same as the following `DocumentationPart` instance:

```
{
    "location" : {
        "type" : "RESOURCE",
        "path": "/"
    },
    "properties" : {
        "description" : "The root resource with an explicit path specification"
    }
}
```



### Inherit content from an API entity of more general specifications
<a name="api-gateway-documenting-api-content-inheritance"></a>

The default value of an optional `location` field provides a patterned description of an API entity. Using the default value in the `location` object, you can add a general description in the `properties` map to a `DocumentationPart` instance with this type of `location` pattern. API Gateway extracts the applicable OpenAPI documentation attributes from the `DocumentationPart` of the generic API entity and injects them into a specific API entity with the `location` fields matching the general `location` pattern, or matching the exact value, unless the specific entity already has a `DocumentationPart` instance associated with it. This behavior is also known as content inheritance from an API entity of more general specifications. 

Content inheritance does not apply to certain API entity types. See the table below for details.

When an API entity matches more than one `DocumentationPart`'s location pattern, the entity will inherit the documentation part with the location fields of the highest precedence and specificities. The order of precedence is `path` > `statusCode`. For matching with the `path` field, API Gateway chooses the entity with the most specific path value. The following table shows this with a few examples.


| Case | `path` | `statusCode` | `name` | Remarks | 
| --- | --- | --- | --- | --- | 
| 1 | /pets | \$1 | id |  Documentation associated with this location pattern will be inherited by entities matching the location pattern.  | 
| 2 | /pets | 200 | id |  Documentation associated with this location pattern will be inherited by entities matching the location pattern when both Case 1 and Case 2 are matched, because Case 2 is more specific than Case 1.   | 
| 3 | /pets/petId | \$1 | id |  Documentation associated with this location pattern will be inherited by entities matching the location pattern when Cases 1, 2, and 3 are matched, because Case 3 has a higher precedence than Case 2 and is more specific than Case 1.  | 

Here is another example to contrast a more generic `DocumentationPart` instance to a more specific one. The following general error message of `"Invalid request error"` is injected into the OpenAPI definitions of the `400` error responses, unless overridden. 

```
{
    "location" : {
        "type" : "RESPONSE",
        "statusCode": "400"
    },
    "properties" : {
        "description" : "Invalid request error."
    }"
}
```

With the following overwrite, the `400` responses to any methods on the `/pets` resource has a description of `"Invalid petId specified"` instead. 

```
{
    "location" : {
        "type" : "RESPONSE",
        "path": "/pets",
        "statusCode": "400"
    },
    "properties" : "{
        "description" : "Invalid petId specified."
    }"
}
```

### Valid location fields of `DocumentationPart`
<a name="api-gateway-documenting-api-content-representation-target-specification"></a>

The following table shows the valid and required fields as well as applicable default values of a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource that is associated with a given type of API entities.


| API entity | Valid location fields | Required location fields | Default field values | Inheritable content | 
| --- | --- | --- | --- | --- | 
| [API](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html) |  <pre>{<br />    "location": {<br />        "type": "API" <br />    }, <br />    ... <br />}</pre>  | type | N/A | No | 
| [Resource](https://docs.aws.amazon.com/apigateway/latest/api/API_Resource.html) |  <pre>{ <br />    "location": { <br />        "type": "RESOURCE", <br />        "path": "resource_path" <br />    }, <br />    ... <br />}</pre>  | type | The default value of path is /.  | No | 
| [Method](https://docs.aws.amazon.com/apigateway/latest/api/API_Method.html) |  <pre>{ <br />    "location": { <br />        "type": "METHOD", <br />        "path": "resource_path", <br />        "method": "http_verb" <br />    }, <br />    ... <br />}</pre>  | type | The default values of path and method are / and \$1, respectively.  | Yes, matching path by prefix and matching method of any values.  | 
| Query parameter |  <pre>{ <br />    "location": { <br />        "type": "QUERY_PARAMETER", <br />        "path": "resource_path", <br />        "method": "HTTP_verb",<br />        "name": "query_parameter_name" <br />    }, <br />    ... <br />}</pre>  | type | The default values of path and method are / and \$1, respectively.  | Yes, matching path by prefix and matching method by exact values. | 
| Request body |  <pre>{ <br />    "location": { <br />        "type": "REQUEST_BODY", <br />        "path": "resource_path", <br />        "method": "http_verb" <br />    }, <br />    ... <br />}</pre>  | type | The default values of path, and method are /and \$1, respectively.  | Yes, matching path by prefix, and matching method by exact values. | 
| Request header parameter |  <pre>{ <br />    "location": { <br />        "type": "REQUEST_HEADER", <br />        "path": "resource_path", <br />        "method": "HTTP_verb",<br />        "name": "header_name" <br />    }, <br />    ... <br />}</pre>  | type, name | The default values of path and method are / and \$1, respectively.  | Yes, matching path by prefix and matching method by exact values. | 
| Request path parameter |  <pre>{ <br />    "location": { <br />        "type": "PATH_PARAMETER", <br />        "path": "resource/{path_parameter_name}", <br />        "method": "HTTP_verb",<br />        "name": "path_parameter_name" <br />    }, <br />    ... <br />}</pre>  | type, name | The default values of path and method are / and \$1, respectively.  | Yes, matching path by prefix and matching method by exact values. | 
| Response |  <pre>{ <br />    "location": { <br />        "type": "RESPONSE", <br />        "path": "resource_path", <br />        "method": "http_verb", <br />        "statusCode": "status_code" <br />    }, <br />    ... <br />}</pre>  | type | The default values of path, method, and statusCode are /, \$1 and \$1, respectively.  | Yes, matching path by prefix and matching method and statusCode by exact values. | 
| Response header |  <pre>{ <br />    "location": { <br />        "type": "RESPONSE_HEADER", <br />        "path": "resource_path", <br />        "method": "http_verb", <br />        "statusCode": "status_code", <br />        "name": "header_name" <br />    }, <br />    ... <br />}</pre>  | type, name | The default values of path, method and statusCode are /, \$1 and \$1, respectively.  | Yes, matching path by prefix and matching method, and statusCode by exact values. | 
| Response body |  <pre>{ <br />    "location": { <br />        "type": "RESPONSE_BODY", <br />        "path": "resource_path", <br />        "method": "http_verb", <br />        "statusCode": "status_code" <br />    }, <br />    ... <br />}</pre>  | type | The default values of path, method and statusCode are /, \$1 and \$1, respectively.  | Yes, matching path by prefix and matching method, and statusCode by exact values. | 
| [Authorizer](https://docs.aws.amazon.com/apigateway/latest/api/API_Authorizer.html) |  <pre>{ <br />    "location": { <br />        "type": "AUTHORIZER", <br />        "name": "authorizer_name" <br />    }, <br />    ... <br />}</pre>  | type | N/A | No | 
| [Model](https://docs.aws.amazon.com/apigateway/latest/api/API_Model.html) |  <pre>{ <br />    "location": { <br />        "type": "MODEL", <br />        "name": "model_name" <br />    }, <br />    ... <br />}</pre>  | type | N/A | No | 

## Documentation versions
<a name="api-gateway-documenting-api-content-representation-documentation-versions"></a>

A documentation version is a snapshot of the [DocumentationParts](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) collection of an API and is tagged with a version identifier. Publishing the documentation of an API involves creating a documentation version, associating it with an API stage, and exporting that stage-specific version of the API documentation to an external OpenAPI file. In API Gateway, a documentation snapshot is represented as a [DocumentationVersion](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationVersion.html) resource. 

As you update an API, you create new versions of the API. In API Gateway, you maintain all the documentation versions using the [DocumentationVersions](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationVersion.html) collection.

# Document an API using the API Gateway console
<a name="api-gateway-documenting-api-quick-start-with-console"></a>

In this section, we describe how to create and maintain documentation parts of an API using the API Gateway console. 

A prerequisite for creating and editing the documentation of an API is that you must have already created the API. In this section, we use the [PetStore](http://petstore-demo-endpoint.execute-api.com/petstore/pets) API as an example. To create an API using the API Gateway console, follow the instructions in [Tutorial: Create a REST API by importing an example](api-gateway-create-api-from-example.md). 

**Topics**
+ [Document the `API` entity](#api-gateway-document-api-add-document-part-for-api-entity-with-console)
+ [Document a `RESOURCE` entity](#api-gateway-document-api-add-document-part-for-resource-entity-with-console)
+ [Document a `METHOD` entity](#api-gateway-document-api-add-document-part-for-method-entity-with-console)
+ [Document a `QUERY_PARAMETER` entity](#api-gateway-document-api-add-document-part-for-request-query-entity-with-console)
+ [Document a `PATH_PARAMETER` entity](#api-gateway-document-api-add-document-part-for-path-parameter-entity-with-console)
+ [Document a `REQUEST_HEADER` entity](#api-gateway-document-api-add-document-part-for-request-header-entity-with-console)
+ [Document a `REQUEST_BODY` entity](#api-gateway-document-api-add-document-part-for-request-body-entity-with-console)
+ [Document a `RESPONSE` entity](#api-gateway-document-api-add-document-part-for-response-with-console)
+ [Document a `RESPONSE_HEADER` entity](#api-gateway-document-api-add-document-part-for-response-header-entity-with-console)
+ [Document a `RESPONSE_BODY` entity](#api-gateway-document-api-add-document-part-for-response-body-entity-with-console)
+ [Document a `MODEL` entity](#api-gateway-document-api-add-document-part-for-model-entity-with-console)
+ [Document an `AUTHORIZER` entity](#api-gateway-document-api-add-document-part-for-authorizer-entity-with-console)

## Document the `API` entity
<a name="api-gateway-document-api-add-document-part-for-api-entity-with-console"></a>

To add a new documentation part for the `API` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **API**.

   If a documentation part was not created for the `API`, you get the documentation part's `properties` map editor. Enter the following `properties` map in the text editor. 

   ```
   {
     "info": {
       "description": "Your first API Gateway API.",
       "contact": {
           "name": "John Doe",
           "email": "john.doe@api.com"
       }
     }
   }
   ```
**Note**  
 You do not need to encode the `properties` map into a JSON string. The API Gateway console stringifies the JSON object for you. 

1. Choose **Create documentation part**.

To add a new documentation part for the `API` entity in the **Resources** pane, do the following:

1. In the main navigation pane, choose **Resources**.

1. Choose the **API actions** menu, and then choose **Update API documentation**.

      
![\[Edit documentation for the API entity in the API Gateway console\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/document-api-entity-using-new-console.png)

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. Select the name of your API, and then on the API card, choose **Edit**.

## Document a `RESOURCE` entity
<a name="api-gateway-document-api-add-document-part-for-resource-entity-with-console"></a>

 To add a new documentation part for a `RESOURCE` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Resource**.

1. For **Path**, enter a path.

1. Enter a description in the text editor, for example:

   ```
   {
       "description": "The PetStore's root resource."
   }
   ```

1. Choose **Create documentation part**. You can create documentation for an unlisted resource.

1.  If required, repeat these steps to add or edit another documentation part.

To add a new documentation part for a `RESOURCE` entity in the **Resources** pane, do the following:

1. In the main navigation pane, choose **Resources**.

1. Choose the resource, and then choose **Update documentation**.

      
![\[Edit documentation for the resource entity in the API Gateway console\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/document-resource-entity-using-new-console.png)

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. Select the resource containing your documentation part, and then choose **Edit**.

## Document a `METHOD` entity
<a name="api-gateway-document-api-add-document-part-for-method-entity-with-console"></a>

 To add a new documentation part for a `METHOD` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Method**.

1. For **Path**, enter a path.

1. For **Method**, select an HTTP verb.

1. Enter a description in the text editor, for example:

   ```
   {
     "tags" : [ "pets" ],
     "summary" : "List all pets"
   }
   ```

1. Choose **Create documentation part**. You can create documentation for an unlisted method.

1.  If required, repeat these steps to add or edit another documentation part.

To add a new documentation part for a `METHOD` entity in the **Resources** pane, do the following:

1. In the main navigation pane, choose **Resources**.

1. Choose the method, and then choose **Update documentation**.

      
![\[Edit documentation for the method entity in the API Gateway console\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/document-method-entity-using-new-console.png)

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the method or select the resource containing the method, and then use the search bar to find and select your documentation part.

1.  Choose **Edit**.

## Document a `QUERY_PARAMETER` entity
<a name="api-gateway-document-api-add-document-part-for-request-query-entity-with-console"></a>

 To add a new documentation part for a `QUERY_PARAMETER` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Query parameter**.

1. For **Path**, enter a path.

1. For **Method**, select an HTTP verb.

1. For **Name**, enter a name.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted query parameter.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the query parameter or select the resource containing the query parameter, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `PATH_PARAMETER` entity
<a name="api-gateway-document-api-add-document-part-for-path-parameter-entity-with-console"></a>

 To add a new documentation part for a `PATH_PARAMETER` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Path parameter**.

1. For **Path**, enter a path.

1. For **Method**, select an HTTP verb.

1. For **Name**, enter a name.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted path parameter.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the path parameter or select the resource containing the path parameter, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `REQUEST_HEADER` entity
<a name="api-gateway-document-api-add-document-part-for-request-header-entity-with-console"></a>

 To add a new documentation part for a `REQUEST_HEADER` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Request header**.

1. For **Path**, enter a path for the request header.

1. For **Method**, select an HTTP verb.

1. For **Name**, enter a name.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted request header.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the request header or select the resource containing the request header, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `REQUEST_BODY` entity
<a name="api-gateway-document-api-add-document-part-for-request-body-entity-with-console"></a>

 To add a new documentation part for a `REQUEST_BODY` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Request body**.

1. For **Path**, enter a path for the request body.

1. For **Method**, select an HTTP verb.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted request body.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the request body or select the resource containing the request body, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `RESPONSE` entity
<a name="api-gateway-document-api-add-document-part-for-response-with-console"></a>

 To add a new documentation part for a `RESPONSE` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Response (status code)**.

1. For **Path**, enter a path for the response.

1. For **Method**, select an HTTP verb.

1. For **Status code**, enter an HTTP status code.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted response status code.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the response status code or select the resource containing the response status code, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `RESPONSE_HEADER` entity
<a name="api-gateway-document-api-add-document-part-for-response-header-entity-with-console"></a>

 To add a new documentation part for a `RESPONSE_HEADER` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Response header**.

1. For **Path**, enter a path for the response header.

1. For **Method**, select an HTTP verb.

1. For **Status code**, enter an HTTP status code.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted response header.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the response header or select the resource containing the response header, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `RESPONSE_BODY` entity
<a name="api-gateway-document-api-add-document-part-for-response-body-entity-with-console"></a>

 To add a new documentation part for a `RESPONSE_BODY` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Response body**.

1. For **Path**, enter a path for the response body.

1. For **Method**, select an HTTP verb.

1. For **Status code**, enter an HTTP status code.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for an unlisted response body.

1.  If required, repeat these steps to add or edit another documentation part.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Resources and methods** tab.

1. You can select the response body or select the resource containing the response body, and then use the search bar to find and select your documentation part.

1. Choose **Edit**.

## Document a `MODEL` entity
<a name="api-gateway-document-api-add-document-part-for-model-entity-with-console"></a>

Documenting a `MODEL` entity involves creating and managing `DocumentPart` instances for the model and each of the model's `properties`'. For example, for the `Error` model that comes with every API by default has the following schema definition,

```
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "Error Schema",
  "type" : "object",
  "properties" : {
    "message" : { "type" : "string" }
  }
}
```

 and requires two `DocumentationPart` instances, one for the `Model` and the other for its `message` property:

```
{
  "location": {
    "type": "MODEL",
    "name": "Error"
  },
  "properties": {
    "title": "Error Schema",
    "description": "A description of the Error model"
  }
}
```

and

```
{
  "location": {
    "type": "MODEL",
    "name": "Error.message"
  },
  "properties": {
    "description": "An error message."
  }
}
```

When the API is exported, the `DocumentationPart`'s properties will override the values in the original schema.

 To add a new documentation part for a `MODEL` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Model**.

1. For **Name**, enter a name for the model.

1. Enter a description in the text editor.

1. Choose **Create documentation part**. You can create documentation for unlisted models.

1.  If required, repeat these steps to add or edit a documentation part to other models.

To add a new documentation part for a `MODEL` entity in the **Models** pane, do the following:

1. In the main navigation pane, choose **Models**.

1. Choose the model, and then choose **Update documentation**.

      
![\[Edit documentation for the model entity in the API Gateway console\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/document-model-entity-using-new-console.png)

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Models** tab.

1. Use the search bar or select the model, and then choose **Edit**.

## Document an `AUTHORIZER` entity
<a name="api-gateway-document-api-add-document-part-for-authorizer-entity-with-console"></a>

 To add a new documentation part for an `AUTHORIZER` entity, do the following:

1. In the main navigation pane, choose **Documentation**, and then choose **Create documentation part**.

1. For **Documentation type**, select **Authorizer**.

1. For **Name**, enter the name of your authorizer.

1. Enter a description in the text editor. Specify a value for the valid `location` field for the authorizer.

1. Choose **Create documentation part**. You can create documentation for unlisted authorizers.

1.  If required, repeat these steps to add or edit a documentation part to other authorizers.

To edit an existing documentation part, do the following:

1. In the **Documentation** pane, choose the **Authorizers** tab.

1. Use the search bar or select the authorizer, and then choose **Edit**.

# Publish API documentation using the API Gateway console
<a name="apigateway-documenting-api-with-console"></a>

The following procedure describes how to publish a documentation version.

**To publish a documentation version using the API Gateway console**

1. In the main navigation pane, choose **Documentation**.

1. Choose **Publish documentation**.

1. Set up the publication:

   1. For **Stage**, select a stage.

   1. For **Version**, enter a version identifier, e.g., `1.0.0`.

   1. (Optional) For **Description**, enter a description.

1. Choose **Publish**.

You can now proceed to download the published documentation by exporting the documentation to an external OpenAPI file. To learn more, see [Export a REST API from API Gateway](api-gateway-export-api.md).

# Document an API using the API Gateway REST API
<a name="api-gateway-documenting-api-quick-start-with-restapi"></a>

In this section, we describe how to create and maintain documentation parts of an API using the API Gateway REST API.

Before creating and editing the documentation of an API, first create the API. In this section, we use the [PetStore](http://petstore-demo-endpoint.execute-api.com/petstore/pets) API as an example. To create an API using the API Gateway console, follow the instructions in [Tutorial: Create a REST API by importing an example](api-gateway-create-api-from-example.md). 

**Topics**
+ [Document the `API` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-api)
+ [Document a `RESOURCE` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-resource)
+ [Document a `METHOD` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-method)
+ [Document a `QUERY_PARAMETER` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-query-parameter)
+ [Document a `PATH_PARAMETER` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-path-parameter)
+ [Document a `REQUEST_BODY` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-request-body)
+ [Document a `REQUEST_HEADER` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-request-header)
+ [Document a `RESPONSE` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-response)
+ [Document a `RESPONSE_HEADER` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-response-header)
+ [Document an `AUTHORIZER` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-authorizer)
+ [Document a `MODEL` entity](#api-gateway-documenting-api-quick-start-with-restapi-add-content-to-model)
+ [Update documentation parts](#api-gateway-documenting-api-quick-start-with-restapi-update-content)
+ [List documentation parts](#api-gateway-documenting-api-quick-start-with-restapi-list-parts)

## Document the `API` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-api"></a>

To add documentation for an [API](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html), add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource for the API entity:

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret   

{
    "location" : {
         "type" : "API"
    },
    "properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  ...
  "id": "s2e5xf",
  "location": {
    "path": null,
    "method": null,
    "name": null,
    "statusCode": null,
    "type": "API"
  },
  "properties": "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}"
}
```

If the documentation part has already been added, a `409 Conflict` response returns, containing the error message of `Documentation part already exists for the specified location: type 'API'."` In this case, you must call the [documentationpart:update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateDocumentationPart.html) operation.

```
PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
  "patchOperations" : [ {
    "op" : "replace",
    "path" : "/properties",
    "value" : "{\n\t\"info\": {\n\t\t\"description\" : \"Your first API with Amazon API Gateway.\"\n\t}\n}"
  } ]
}
```

The successful response returns a `200 OK` status code with the payload containing the updated `DocumentationPart` instance in the payload.

## Document a `RESOURCE` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-resource"></a>

To add documentation for the root resource of an API, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the corresponding [Resource](https://docs.aws.amazon.com/apigateway/latest/api/API_Resource.html) resource:

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret   

{
    "location" : {
       "type" : "RESOURCE",
    },
    "properties" : "{\n\t\"description\" : \"The PetStore root resource.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example: 

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/p76vqo"
    }
  },
  "id": "p76vqo",
  "location": {
    "path": "/",
    "method": null,
    "name": null,
    "statusCode": null,
    "type": "RESOURCE"
  },
  "properties": "{\n\t\"description\" : \"The PetStore root resource.\"\n}"
}
```

When the resource path is not specified, the resource is assumed to be the root resource. You can add `"path": "/"` to `properties` to make the specification explicit.

To create documentation for a child resource of an API, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the corresponding [Resource](https://docs.aws.amazon.com/apigateway/latest/api/API_Resource.html) resource:

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "RESOURCE",
         "path" : "/pets"
    },
    "properties": "{\n\t\"description\" : \"A child resource under the root of PetStore.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/qcht86"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/qcht86"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/qcht86"
    }
  },
  "id": "qcht86",
  "location": {
    "path": "/pets",
    "method": null,
    "name": null,
    "statusCode": null,
    "type": "RESOURCE"
  },
  "properties": "{\n\t\"description\" : \"A child resource under the root of PetStore.\"\n}"
}
```

To add documentation for a child resource specified by a path parameter, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the [Resource](https://docs.aws.amazon.com/apigateway/latest/api/API_Resource.html) resource:

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "RESOURCE",
         "path" : "/pets/{petId}"
    },
    "properties": "{\n\t\"description\" : \"A child resource specified by the petId path parameter.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/k6fpwb"
    }
  },
  "id": "k6fpwb",
  "location": {
    "path": "/pets/{petId}",
    "method": null,
    "name": null,
    "statusCode": null,
    "type": "RESOURCE"
  },
  "properties": "{\n\t\"description\" : \"A child resource specified by the petId path parameter.\"\n}"
}
```

**Note**  
The [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) instance of a `RESOURCE` entity cannot be inherited by any of its child resources.

## Document a `METHOD` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-method"></a>

To add documentation for a method of an API, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the corresponding [Method](https://docs.aws.amazon.com/apigateway/latest/api/API_Method.html) resource:

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "METHOD",
         "path" : "/pets",
         "method" : "GET"
    },
    "properties": "{\n\t\"summary\" : \"List all pets.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example: 

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    }
  },
  "id": "o64jbj",
  "location": {
    "path": "/pets",
    "method": "GET",
    "name": null,
    "statusCode": null,
    "type": "METHOD"
  },
  "properties": "{\n\t\"summary\" : \"List all pets.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    }
  },
  "id": "o64jbj",
  "location": {
    "path": "/pets",
    "method": "GET",
    "name": null,
    "statusCode": null,
    "type": "METHOD"
  },
  "properties": "{\n\t\"summary\" : \"List all pets.\"\n}"
}
```

If the `location.method` field is not specified in the preceding request, it is assumed to be `ANY` method that is represented by a wild card `*` character.

To update the documentation content of a `METHOD` entity, call the [documentationpart:update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateDocumentationPart.html) operation, supplying a new `properties` map:

```
PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
  "patchOperations" : [ {
    "op" : "replace",
    "path" : "/properties",
    "value" : "{\n\t\"tags\" : [ \"pets\" ], \n\t\"summary\" : \"List all pets.\"\n}"
  } ]
}
```

The successful response returns a `200 OK` status code with the payload containing the updated `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/o64jbj"
    }
  },
  "id": "o64jbj",
  "location": {
    "path": "/pets",
    "method": "GET",
    "name": null,
    "statusCode": null,
    "type": "METHOD"
  },
  "properties": "{\n\t\"tags\" : [ \"pets\" ], \n\t\"summary\" : \"List all pets.\"\n}"
}
```

## Document a `QUERY_PARAMETER` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-query-parameter"></a>

To add documentation for a request query parameter, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the `QUERY_PARAMETER` type, with the valid fields of `path` and `name`.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "QUERY_PARAMETER",
         "path" : "/pets",
         "method" : "GET",
         "name" : "page"
    },
    "properties": "{\n\t\"description\" : \"Page number of results to return.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/h9ht5w"
    }
  },
  "id": "h9ht5w",
  "location": {
    "path": "/pets",
    "method": "GET",
    "name": "page",
    "statusCode": null,
    "type": "QUERY_PARAMETER"
  },
  "properties": "{\n\t\"description\" : \"Page number of results to return.\"\n}"
}
```

The documentation part's `properties` map of a `QUERY_PARAMETER` entity can be inherited by one of its child `QUERY_PARAMETER` entities. For example, if you add a `treats` resource after `/pets/{petId}`, enable the `GET` method on `/pets/{petId}/treats`, and expose the `page` query parameter, this child query parameter inherits the `DocumentationPart`'s `properties` map from the like-named query parameter of the `GET /pets` method, unless you explicitly add a `DocumentationPart` resource to the `page` query parameter of the `GET /pets/{petId}/treats` method.

## Document a `PATH_PARAMETER` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-path-parameter"></a>

To add documentation for a path parameter, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource for the `PATH_PARAMETER` entity.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "PATH_PARAMETER",
         "path" : "/pets/{petId}",
         "method" : "*",
         "name" : "petId"
    },
    "properties": "{\n\t\"description\" : \"The id of the pet to retrieve.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/ckpgog"
    }
  },
  "id": "ckpgog",
  "location": {
    "path": "/pets/{petId}",
    "method": "*",
    "name": "petId",
    "statusCode": null,
    "type": "PATH_PARAMETER"
  },
  "properties": "{\n  \"description\" : \"The id of the pet to retrieve\"\n}"
}
```

## Document a `REQUEST_BODY` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-request-body"></a>

To add documentation for a request body, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource for the request body.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "REQUEST_BODY",
         "path" : "/pets",
         "method" : "POST"
    },
    "properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/kgmfr1"
    }
  },
  "id": "kgmfr1",
  "location": {
    "path": "/pets",
    "method": "POST",
    "name": null,
    "statusCode": null,
    "type": "REQUEST_BODY"
  },
  "properties": "{\n\t\"description\" : \"A Pet object to be added to PetStore.\"\n}"
}
```

## Document a `REQUEST_HEADER` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-request-header"></a>

To add documentation for a request header, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource for the request header.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "REQUEST_HEADER",
         "path" : "/pets",
         "method" : "GET",
         "name" : "x-my-token"
    },
    "properties": "{\n\t\"description\" : \"A custom token used to authorization the method invocation.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/h0m3uf"
    }
  },
  "id": "h0m3uf",
  "location": {
    "path": "/pets",
    "method": "GET",
    "name": "x-my-token",
    "statusCode": null,
    "type": "REQUEST_HEADER"
  },
  "properties": "{\n\t\"description\" : \"A custom token used to authorization the method invocation.\"\n}"
}
```

## Document a `RESPONSE` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-response"></a>

To add documentation for a response of a status code, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the corresponding [MethodResponse](https://docs.aws.amazon.com/apigateway/latest/api/API_MethodResponse.html) resource.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location": {
      "path": "/",
      "method": "*",
      "name": null,
      "statusCode": "200",
      "type": "RESPONSE"
    },
    "properties": "{\n  \"description\" : \"Successful operation.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example:

```
{
    "_links": {
        "self": {
            "href": "/restapis/4wk1k4onj3/documentation/parts/lattew"
        },
        "documentationpart:delete": {
            "href": "/restapis/4wk1k4onj3/documentation/parts/lattew"
        },
        "documentationpart:update": {
            "href": "/restapis/4wk1k4onj3/documentation/parts/lattew"
        }
    },
    "id": "lattew",
    "location": {
        "path": "/",
        "method": "*",
        "name": null,
        "statusCode": "200",
        "type": "RESPONSE"
    },
    "properties": "{\n  \"description\" : \"Successful operation.\"\n}"
}
```

## Document a `RESPONSE_HEADER` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-response-header"></a>

To add documentation for a response header, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource for the response header.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

  "location": {
    "path": "/",
    "method": "GET",
    "name": "Content-Type",
    "statusCode": "200",
    "type": "RESPONSE_HEADER"
  },
  "properties": "{\n  \"description\" : \"Media type of request\"\n}"
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example: 

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/fev7j7"
    }
  },
  "id": "fev7j7",
  "location": {
    "path": "/",
    "method": "GET",
    "name": "Content-Type",
    "statusCode": "200",
    "type": "RESPONSE_HEADER"
  },
  "properties": "{\n  \"description\" : \"Media type of request\"\n}"
}
```

The documentation of this `Content-Type` response header is the default documentation for the `Content-Type` headers of any responses of the API. 

## Document an `AUTHORIZER` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-authorizer"></a>

To add documentation for an API authorizer, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the specified authorizer.

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "AUTHORIZER",
         "name" : "myAuthorizer"
    },
    "properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example: 

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/pw3qw3"
    }
  },
  "id": "pw3qw3",
  "location": {
    "path": null,
    "method": null,
    "name": "myAuthorizer",
    "statusCode": null,
    "type": "AUTHORIZER"
  },
  "properties": "{\n\t\"description\" : \"Authorizes invocations of configured methods.\"\n}"
}
```

**Note**  
The [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) instance of an `AUTHORIZER` entity cannot be inherited by any of its child resources.

## Document a `MODEL` entity
<a name="api-gateway-documenting-api-quick-start-with-restapi-add-content-to-model"></a>

 Documenting a `MODEL` entity involves creating and managing `DocumentPart` instances for the model and each of the model's `properties`'. For example, for the `Error` model that comes with every API by default has the following schema definition, 

```
{
  "$schema" : "http://json-schema.org/draft-04/schema#",
  "title" : "Error Schema",
  "type" : "object",
  "properties" : {
    "message" : { "type" : "string" }
  }
}
```

 and requires two `DocumentationPart` instances, one for the `Model` and the other for its `message` property: 

```
{
  "location": {
    "type": "MODEL",
    "name": "Error"
  },
  "properties": {
    "title": "Error Schema",
    "description": "A description of the Error model"
  }
}
```

and

```
{
  "location": {
    "type": "MODEL",
    "name": "Error.message"
  },
  "properties": {
    "description": "An error message."
  }
}
```

When the API is exported, the `DocumentationPart`'s properties will override the values in the original schema. 

 To add documentation for an API model, add a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) resource targeted for the specified model. 

```
POST /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "location" : {
         "type" : "MODEL",
         "name" : "Pet"
    },
    "properties": "{\n\t\"description\" : \"Data structure of a Pet object.\"\n}"
}
```

If successful, the operation returns a `201 Created` response containing the newly created `DocumentationPart` instance in the payload. For example: 

```
{
  "_links": {
    "curies": {
      "href": "http://docs.aws.amazon.com/apigateway/latest/developerguide/restapi-documentationpart-{rel}.html",
      "name": "documentationpart",
      "templated": true
    },
    "self": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq"
    },
    "documentationpart:delete": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq"
    },
    "documentationpart:update": {
      "href": "/restapis/4wk1k4onj3/documentation/parts/lkn4uq"
    }
  },
  "id": "lkn4uq",
  "location": {
    "path": null,
    "method": null,
    "name": "Pet",
    "statusCode": null,
    "type": "MODEL"
  },
  "properties": "{\n\t\"description\" : \"Data structure of a Pet object.\"\n}"
}
```

Repeat the same step to create a DocumentationPart instance for any of the model's properties.

**Note**  
The [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) instance of a `MODEL` entity cannot be inherited by any of its child resources.

## Update documentation parts
<a name="api-gateway-documenting-api-quick-start-with-restapi-update-content"></a>

 To update the documentation parts of any type of API entities, submit a PATCH request on a [DocumentationPart](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) instance of a specified part identifier to replace the existing `properties` map with a new one. 

```
PATCH /restapis/4wk1k4onj3/documentation/parts/part_id HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret
                
{
  "patchOperations" : [ {
    "op" : "replace",
    "path" : "RESOURCE_PATH",
    "value" : "NEW_properties_VALUE_AS_JSON_STRING"
  } ]
}
```

The successful response returns a `200 OK` status code with the payload containing the updated `DocumentationPart` instance in the payload.

You can update multiple documentation parts in a single `PATCH` request.

## List documentation parts
<a name="api-gateway-documenting-api-quick-start-with-restapi-list-parts"></a>

 To list the documentation parts of any type of API entities, submit a GET request on a [DocumentationParts](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) collection. 

```
GET /restapis/restapi_id/documentation/parts HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret
```

The successful response returns a `200 OK` status code with the payload containing the available `DocumentationPart` instances in the payload.

# Publish API documentation using the API Gateway REST API
<a name="api-gateway-documenting-api-quick-start-publishing"></a>

To publish the documentation for an API, create, update, or get a documentation snapshot, and then associate the documentation snapshot with an API stage. When creating a documentation snapshot, you can also associate it with an API stage at the same time.

**Topics**
+ [Create a documentation snapshot and associate it with an API stage](#api-gateway-documenting-api-publishing-create-documentation-version-with-stage)
+ [Create a documentation snapshot](#api-gateway-documenting-api-publishing-create-documentation-version)
+ [Update a documentation snapshot](#api-gateway-documenting-api-publishing-update-documentation-version)
+ [Get a documentation snapshot](#api-gateway-documenting-api-publishing-get-documentation-version)
+ [Associate a documentation snapshot with an API stage](#api-gateway-documenting-api-publishing-stage-association)
+ [Download a documentation snapshot associated with a stage](#api-gateway-documenting-api-publishing-export-documentation-version)

## Create a documentation snapshot and associate it with an API stage
<a name="api-gateway-documenting-api-publishing-create-documentation-version-with-stage"></a>

To create a snapshot of an API's documentation parts and associate it with an API stage at the same time, submit the following `POST` request:

```
POST /restapis/restapi_id/documentation/versions HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "documentationVersion" : "1.0.0",
    "stageName": "prod",
    "description" : "My API Documentation v1.0.0"
}
```

If successful, the operation returns a `200 OK` response, containing the newly created `DocumentationVersion` instance as the payload.

Alternatively, you can create a documentation snapshot without associating it with an API stage first and then call [restapi:update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html) to associate the snapshot with a specified API stage. You can also update or query an existing documentation snapshot and then update its stage association. We show the steps in the next four sections.

## Create a documentation snapshot
<a name="api-gateway-documenting-api-publishing-create-documentation-version"></a>

To create a snapshot of an API's documentation parts, create a new [DocumentationVersion](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationVersion.html) resource and add it to the [DocumentationVersions](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationVersion.html) collection of the API:

```
POST /restapis/restapi_id/documentation/versions HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "documentationVersion" : "1.0.0",
    "description" : "My API Documentation v1.0.0"
}
```

If successful, the operation returns a `200 OK` response, containing the newly created `DocumentationVersion` instance as the payload.

## Update a documentation snapshot
<a name="api-gateway-documenting-api-publishing-update-documentation-version"></a>

You can only update a documentation snapshot by modifying the `description` property of the corresponding [DocumentationVersion](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationVersion.html) resource. The following example shows how to update the description of the documentation snapshot as identified by its version identifier, `version`, e.g., `1.0.0`.

```
PATCH /restapis/restapi_id/documentation/versions/version HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "patchOperations": [{
        "op": "replace",
        "path": "/description",
        "value": "My API for testing purposes."
    }]
}
```

If successful, the operation returns a `200 OK` response, containing the updated `DocumentationVersion` instance as the payload. 

## Get a documentation snapshot
<a name="api-gateway-documenting-api-publishing-get-documentation-version"></a>

To get a documentation snapshot, submit a `GET` request against the specified [DocumentationVersion](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationVersion.html) resource. The following example shows how to get a documentation snapshot of a given version identifier, 1.0.0.

```
GET /restapis/<restapi_id>/documentation/versions/1.0.0 HTTP/1.1
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret
```

## Associate a documentation snapshot with an API stage
<a name="api-gateway-documenting-api-publishing-stage-association"></a>

To publish the API documentation, associate a documentation snapshot with an API stage. You must have already created an API stage before associating the documentation version with the stage.

To associate a documentation snapshot with an API stage using the [API Gateway REST API](https://docs.aws.amazon.com/apigateway/latest/api/), call the [stage:update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateStage.html) operation to set the desired documentation version on the `stage.documentationVersion` property:

```
PATCH /restapis/RESTAPI_ID/stages/STAGE_NAME
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
    "patchOperations": [{
        "op": "replace",
        "path": "/documentationVersion",
        "value": "VERSION_IDENTIFIER"
    }]
}
```

## Download a documentation snapshot associated with a stage
<a name="api-gateway-documenting-api-publishing-export-documentation-version"></a>

After a version of the documentation parts is associated with a stage, you can export the documentation parts together with the API entity definitions, to an external file, using the API Gateway console, the API Gateway REST API, one of its SDKs, or the AWS CLI for API Gateway. The process is the same as for exporting the API. The exported file format can be JSON or YAML. 

Using the API Gateway REST API, you can also explicitly set the `extension=documentation,integrations,authorizers` query parameter to include the API documentation parts, API integrations and authorizers in an API export. By default, documentation parts are included, but integrations and authorizers are excluded, when you export an API. The default output from an API export is suited for distribution of the documentation.

To export the API documentation in an external JSON OpenAPI file using the API Gateway REST API, submit the following `GET` request:

```
GET /restapis/restapi_id/stages/stage_name/exports/swagger?extensions=documentation HTTP/1.1
Accept: application/json
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret
```

Here, the `x-amazon-apigateway-documentation` object contains the documentation parts and the API entity definitions contains the documentation properties supported by OpenAPI. The output does not include details of integration or Lambda authorizers (formerly known as custom authorizers). To include both details, set `extensions=integrations,authorizers,documentation`. To include details of integrations but not of authorizers, set `extensions=integrations,documentation`. 

You must set the `Accept:application/json` header in the request to output the result in a JSON file. To produce the YAML output, change the request header to `Accept:application/yaml`. 

As an example, we will look at an API that exposes a simple `GET` method on the root resource (`/`). This API has four API entities defined in an OpenAPI definition file, one for each of the `API`, `MODEL`, `METHOD`, and `RESPONSE` types. A documentation part has been added to each of the `API`, `METHOD`, and `RESPONSE` entities. Calling the preceding documentation-exporting command, we get the following output, with the documentation parts listed within the `x-amazon-apigateway-documentation` object as an extension to a standard OpenAPI file.

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

```
{
   "openapi": "3.0.0",
   "info": {
      "description": "API info description",
      "version": "2016-11-22T22:39:14Z",
      "title": "doc",
      "x-bar": "API info x-bar"
   },
   "paths": {
      "/": {
         "get": {
            "description": "Method description.",
            "responses": {
               "200": {
                  "description": "200 response",
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     }
                  }
               }
            },
            "x-example": "x- Method example"
         },
         "x-bar": "resource x-bar"
      }
   },
   "x-amazon-apigateway-documentation": {
      "version": "1.0.0",
      "createdDate": "2016-11-22T22:41:40Z",
      "documentationParts": [
         {
            "location": {
               "type": "API"
            },
            "properties": {
               "description": "API description",
               "foo": "API foo",
               "x-bar": "API x-bar",
               "info": {
                  "description": "API info description",
                  "version": "API info version",
                  "foo": "API info foo",
                  "x-bar": "API info x-bar"
               }
            }
         },
         {
            "location": {
               "type": "METHOD",
               "method": "GET"
            },
            "properties": {
               "description": "Method description.",
               "x-example": "x- Method example",
               "foo": "Method foo",
               "info": {
                  "version": "method info version",
                  "description": "method info description",
                  "foo": "method info foo"
               }
            }
         },
         {
            "location": {
               "type": "RESOURCE"
            },
            "properties": {
               "description": "resource description",
               "foo": "resource foo",
               "x-bar": "resource x-bar",
               "info": {
                  "description": "resource info description",
                  "version": "resource info version",
                  "foo": "resource info foo",
                  "x-bar": "resource info x-bar"
               }
            }
         }
      ]
   },
   "x-bar": "API x-bar",
   "servers": [
      {
         "url": "https://rznaap68yi.execute-api.ap-southeast-1.amazonaws.com/{basePath}",
         "variables": {
            "basePath": {
              "default": "/test"
            }
         }
      }
   ],
   "components": {
      "schemas": {
         "Empty": {
            "type": "object",
            "title": "Empty Schema"
         }
      }
   }
}
```

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

```
{
  "swagger" : "2.0",
  "info" : {
    "description" : "API info description",
    "version" : "2016-11-22T22:39:14Z",
    "title" : "doc",
    "x-bar" : "API info x-bar"
  },
  "host" : "rznaap68yi.execute-api.ap-southeast-1.amazonaws.com",
  "basePath" : "/test",
  "schemes" : [ "https" ],
  "paths" : {
    "/" : {
      "get" : {
        "description" : "Method description.",
        "produces" : [ "application/json" ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "schema" : {
              "$ref" : "#/definitions/Empty"
            }
          }
        },
        "x-example" : "x- Method example"
      },
      "x-bar" : "resource x-bar"
    }
  },
  "definitions" : {
    "Empty" : {
      "type" : "object",
      "title" : "Empty Schema"
    }
  },
  "x-amazon-apigateway-documentation" : {
    "version" : "1.0.0",
    "createdDate" : "2016-11-22T22:41:40Z",
    "documentationParts" : [ {
      "location" : {
        "type" : "API"
      },
      "properties" : {
        "description" : "API description",
        "foo" : "API foo",
        "x-bar" : "API x-bar",
        "info" : {
          "description" : "API info description",
          "version" : "API info version",
          "foo" : "API info foo",
          "x-bar" : "API info x-bar"
        }
      }
    }, {
      "location" : {
        "type" : "METHOD",
        "method" : "GET"
      },
      "properties" : {
        "description" : "Method description.",
        "x-example" : "x- Method example",
        "foo" : "Method foo",
        "info" : {
          "version" : "method info version",
          "description" : "method info description",
          "foo" : "method info foo"
        }
      }
    }, {
      "location" : {
        "type" : "RESOURCE"
      },
      "properties" : {
        "description" : "resource description",
        "foo" : "resource foo",
        "x-bar" : "resource x-bar",
        "info" : {
          "description" : "resource info description",
          "version" : "resource info version",
          "foo" : "resource info foo",
          "x-bar" : "resource info x-bar"
        }
      }
    } ]
  },
  "x-bar" : "API x-bar"
}
```

------

For an OpenAPI-compliant attribute defined in the `properties` map of a documentation part, API Gateway inserts the attribute into the associated API entity definition. An attribute of `x-something` is a standard OpenAPI extension. This extension gets propagated into the API entity definition. For example, see the `x-example` attribute for the `GET` method. An attribute like `foo` is not part of the OpenAPI specification and is not injected into its associated API entity definitions. 

If a documentation-rendering tool (e.g., [OpenAPI UI](https://swagger.io/tools/swagger-ui/)) parses the API entity definitions to extract documentation attributes, any non OpenAPI-compliant `properties` attributes of a `DocumentationPart`' instance are not available for the tool. However, if a documentation-rendering tool parses the `x-amazon-apigateway-documentation` object to get content, or if the tool calls [restapi:documentation-parts](https://docs.aws.amazon.com/apigateway/latest/api/API_DocumentationPart.html) and [documenationpart:by-id](https://docs.aws.amazon.com/apigateway/latest/api/API_GetDocumentationPart.html) to retrieve documentation parts from API Gateway, all the documentation attributes are available for the tool to display.

To export the documentation with API entity definitions containing integration details to a JSON OpenAPI file, submit the following `GET` request:

 

```
GET /restapis/restapi_id/stages/stage_name/exports/swagger?extensions=integrations,documentation HTTP/1.1
Accept: application/json
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret
```

To export the documentation with API entity definitions containing details of integrations and authorizers to a YAML OpenAPI file, submit the following `GET` request:

 

```
GET /restapis/restapi_id/stages/stage_name/exports/swagger?extensions=integrations,authorizers,documentation HTTP/1.1
Accept: application/yaml
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret
```

To use the API Gateway console to export and download the published documentation of an API, follow the instructions in [Export REST API using the API Gateway console](api-gateway-export-api.md#api-gateway-export-api-from-console). 

# Import API documentation
<a name="api-gateway-documenting-api-quick-start-import-export"></a>

 As with importing API entity definitions, you can import documentation parts from an external OpenAPI file into an API in API Gateway. You specify the to-be-imported documentation parts within the [x-amazon-apigateway-documentation object](api-gateway-swagger-extensions-documentation.md) extension in a valid OpenAPI definition file. Importing documentation does not alter the existing API entity definitions.

You have an option to merge the newly specified documentation parts into existing documentation parts in API Gateway or to overwrite the existing documentation parts. In the `MERGE` mode, a new documentation part defined in the OpenAPI file is added to the `DocumentationParts` collection of the API. If an imported `DocumentationPart` already exists, an imported attribute replaces the existing one if the two are different. Other existing documentation attributes remain unaffected. In the `OVERWRITE` mode, the entire `DocumentationParts` collection is replaced according to the imported OpenAPI definition file.

## Importing documentation parts using the API Gateway REST API
<a name="api-gateway-importing-api-with-swagger-file-using-rest-api"></a>

To import API documentation using the API Gateway REST API, call the [documentationpart:import](https://docs.aws.amazon.com/apigateway/latest/api/API_ImportDocumentationParts.html) operation. The following example shows how to overwrite existing documentation parts of an API with a single `GET / ` method, returning a `200 OK` response when successful.

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

```
PUT /restapis/<restapi_id>/documentation/parts&mode=overwrite&failonwarnings=true
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
   "openapi": "3.0.0",
   "info": {
      "description": "description",
      "version": "1",
      "title": "doc"
   },
   "paths": {
      "/": {
         "get": {
            "description": "Method description.",
            "responses": {
               "200": {
                  "description": "200 response",
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Empty"
                        }
                     }
                  }
               }
            }
         }
      }
   },
   "x-amazon-apigateway-documentation": {
      "version": "1.0.3",
      "documentationParts": [
         {
            "location": {
               "type": "API"
            },
            "properties": {
               "description": "API description",
               "info": {
                  "description": "API info description 4",
                  "version": "API info version 3"
               }
            }
         },
         {
            "location": {
               "type": "METHOD",
               "method": "GET"
            },
            "properties": {
               "description": "Method description."
            }
         },
         {
            "location": {
               "type": "MODEL",
               "name": "Empty"
            },
            "properties": {
               "title": "Empty Schema"
            }
         },
         {
            "location": {
               "type": "RESPONSE",
               "method": "GET",
               "statusCode": "200"
            },
            "properties": {
               "description": "200 response"
            }
         }
      ]
   },
   "servers": [
      {
         "url": "/"
      }
   ],
   "components": {
      "schemas": {
         "Empty": {
            "type": "object",
            "title": "Empty Schema"
         }
      }
   }
}
```

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

```
PUT /restapis/<restapi_id>/documentation/parts&mode=overwrite&failonwarnings=true
Host: apigateway.region.amazonaws.com
Content-Type: application/json
X-Amz-Date: YYYYMMDDTttttttZ
Authorization: AWS4-HMAC-SHA256 Credential=access_key_id/YYYYMMDD/region/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=sigv4_secret

{
  "swagger": "2.0",
  "info": {
    "description": "description",
    "version": "1",
    "title": "doc"
  },
  "host": "",
  "basePath": "/",
  "schemes": [
    "https"
  ],
  "paths": {
    "/": {
      "get": {
        "description": "Method description.",
        "produces": [
          "application/json"
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            }
          }
        }
      }
    }
  },
  "definitions": {
    "Empty": {
      "type": "object",
      "title": "Empty Schema"
    }
  },
  "x-amazon-apigateway-documentation": {
    "version": "1.0.3",
    "documentationParts": [
      {
        "location": {
          "type": "API"
        },
        "properties": {
          "description": "API description",
          "info": {
            "description": "API info description 4",
            "version": "API info version 3"
          }
        }
      },
      {
        "location": {
          "type": "METHOD",
          "method": "GET"
        },
        "properties": {
          "description": "Method description."
        }
      },
      {
        "location": {
          "type": "MODEL",
          "name": "Empty"
        },
        "properties": {
          "title": "Empty Schema"
        }
      },
      {
        "location": {
          "type": "RESPONSE",
          "method": "GET",
          "statusCode": "200"
        },
        "properties": {
          "description": "200 response"
        }
      }
    ]
  }
}
```

------

When successful, this request returns a 200 OK response containing the imported `DocumentationPartId` in the payload.

```
{
  "ids": [
    "kg3mth",
    "796rtf",
    "zhek4p",
    "5ukm9s"
  ]
}
```

In addition, you can also call [restapi:import](https://docs.aws.amazon.com/apigateway/latest/api/API_ImportRestApi.html) or [restapi:put](https://docs.aws.amazon.com/apigateway/latest/api/API_PutRestApi.html), supplying the documentation parts in the `x-amazon-apigateway-documentation` object as part of the input OpenAPI file of the API definition. To exclude the documentation parts from the API import, set `ignore=documentation` in the request query parameters.

## Importing documentation parts using the API Gateway console
<a name="api-gateway-importing-api-with-swagger-file-using-console"></a>

The following instructions describe how to import documentation parts.

**To use the console to import documentation parts of an API from an external file**

1. In the main navigation pane, choose **Documentation**.

1. Choose **Import**.

1. If you have existing documentation, select to either **Overwrite** or **Merge** your new documentation.

1. Choose **Choose file** to load a file from a drive, or enter file contents into the file view. For an example, see the payload of the example request in [Importing documentation parts using the API Gateway REST API](#api-gateway-importing-api-with-swagger-file-using-rest-api).

1. Choose how to handle warnings on import. Select either **Fail on warnings** or **Ignore warnings**. For more information, see [Errors and warnings from importing your API into API Gateway](api-gateway-import-api-errors-warnings.md). 

1. Choose **Import**.

# Control access to API documentation in API Gateway
<a name="api-gateway-documenting-api-content-provision-and-consumption"></a>

If you have a dedicated documentation team to write and edit your API documentation, you can configure separate access permissions for your developers (for API development) and for your writers or editors (for content development). This is especially appropriate when a third-party vendor is involved in creating the documentation for you. 

 To grant your documentation team the access to create, update, and publish your API documentation, you can assign the documentation team an IAM role with the following IAM policy, where *account\$1id* is the AWS account ID of your documentation team. 

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [

    {
      "Sid": "StmtDocPartsAddEditViewDelete",
      "Effect": "Allow",
      "Action": [
        "apigateway:GET",
        "apigateway:PUT",
        "apigateway:POST",
        "apigateway:PATCH",
        "apigateway:DELETE"
      ],
      "Resource": [
        "arn:aws:apigateway:us-east-1:111111111111:/restapis/*/documentation/*"
      ]
    }
  ]
}
```

------

 For information on setting permissions to access API Gateway resources, see [How Amazon API Gateway works with IAM](security_iam_service-with-iam.md). 

# Generate SDKs for REST APIs in API Gateway
<a name="how-to-generate-sdk"></a>

To call your REST API in a platform- or language-specific way, you must generate the platform- or language-specific SDK of the API. You generate your SDK after you create, test, and deploy your API to a stage. Currently, API Gateway supports generating an SDK for an API in Java, JavaScript, Java for Android, Objective-C or Swift for iOS, and Ruby.

This section explains how to generate an SDK of an API Gateway API. It also demonstrates how to use the generated SDK in a Java app, a Java for Android app, Objective-C and Swift for iOS apps, and a JavaScript app. 

To facilitate the discussion, we use this API Gateway [API](simple-calc-lambda-api.md), which exposes this [Simple Calculator](simple-calc-nodejs-lambda-function.md) Lambda function. 

Before proceeding, create or import the API and deploy it at least once in API Gateway. For instructions, see [Deploy REST APIs in API Gateway](how-to-deploy-api.md).

**Topics**
+ [Simple calculator Lambda function](simple-calc-nodejs-lambda-function.md)
+ [Simple calculator API in API Gateway](simple-calc-lambda-api.md)
+ [Simple calculator API OpenAPI definition](simple-calc-lambda-api-swagger-definition.md)
+ [Generate the Java SDK of an API in API Gateway](generate-java-sdk-of-an-api.md)
+ [Generate the Android SDK of an API in API Gateway](generate-android-sdk-of-an-api.md)
+ [Generate the iOS SDK of an API in API Gateway](generate-ios-sdk-of-an-api.md)
+ [Generate the JavaScript SDK of a REST API in API Gateway](generate-javascript-sdk-of-an-api.md)
+ [Generate the Ruby SDK of an API in API Gateway](generate-ruby-sdk-of-an-api.md)
+ [Generate SDKs for an API using AWS CLI commands in API Gateway](how-to-generate-sdk-cli.md)

# Simple calculator Lambda function
<a name="simple-calc-nodejs-lambda-function"></a>

As an illustration, we will use a Node.js Lambda function that performs the binary operations of addition, subtraction, multiplication and division. 

**Topics**
+ [Simple calculator Lambda function input format](#simple-calc-lambda-function-input-format)
+ [Simple calculator Lambda function output format](#simple-calc-lambda-function-output-format)
+ [Simple calculator Lambda function implementation](#simple-calc-lambda-function-implementation)

## Simple calculator Lambda function input format
<a name="simple-calc-lambda-function-input-format"></a>

This function takes an input of the following format:

```
{ "a": "Number", "b": "Number", "op": "string"}
```

where `op` can be any of `(+, -, *, /, add, sub, mul, div)`.

## Simple calculator Lambda function output format
<a name="simple-calc-lambda-function-output-format"></a>

When an operation succeeds, it returns the result of the following format:

```
{ "a": "Number", "b": "Number", "op": "string", "c": "Number"}
```

where `c` holds the result of the calculation.

## Simple calculator Lambda function implementation
<a name="simple-calc-lambda-function-implementation"></a>

The implementation of the Lambda function is as follows:

```
export const handler = async function (event, context) {
  console.log("Received event:", JSON.stringify(event));

  if (
    event.a === undefined ||
    event.b === undefined ||
    event.op === undefined
  ) {
    return "400 Invalid Input";
  }

  const res = {};
  res.a = Number(event.a);
  res.b = Number(event.b);
  res.op = event.op;
  if (isNaN(event.a) || isNaN(event.b)) {
    return "400 Invalid Operand";
  }
  switch (event.op) {
    case "+":
    case "add":
      res.c = res.a + res.b;
      break;
    case "-":
    case "sub":
      res.c = res.a - res.b;
      break;
    case "*":
    case "mul":
      res.c = res.a * res.b;
      break;
    case "/":
    case "div":
      if (res.b == 0) {
        return "400 Divide by Zero";
      } else {
        res.c = res.a / res.b;
      }
      break;
    default:
      return "400 Invalid Operator";
  }

  return res;
};
```

# Simple calculator API in API Gateway
<a name="simple-calc-lambda-api"></a>

Our simple calculator API exposes three methods (GET, POST, GET) to invoke the [Simple calculator Lambda function](simple-calc-nodejs-lambda-function.md). A graphical representation of this API is shown as follows:

![\[Simple calculator API for generated SDK\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/simple-calc-api-console-hierarchy-new-console.png)


These three methods show different ways to supply the input for the backend Lambda function to perform the same operation: 
+ The `GET /?a=...&b=...&op=...` method uses the query parameters to specify the input.
+ The `POST /` method uses a JSON payload of `{"a":"Number", "b":"Number", "op":"string"}` to specify the input.
+ The `GET /{a}/{b}/{op}` method uses the path parameters to specify the input.

If not defined, API Gateway generates the corresponding SDK method name by combining the HTTP method and path parts. The root path part (`/`) is referred to as `Api Root`. For example, the default Java SDK method name for the API method of `GET /?a=...&b=...&op=...` is `getABOp`, the default SDK method name for `POST /` is `postApiRoot`, and the default SDK method name for `GET /{a}/{b}/{op}` is `getABOp`. Individual SDKs may customize the convention. Consult the documentation in the generated SDK source for SDK specific method names. 

You can, and should, override the default SDK method names by specifying the [operationName](https://docs.aws.amazon.com/apigateway/latest/api/API_Method.html#operationName) property on each API method. You can do so when [creating the API method](https://docs.aws.amazon.com/apigateway/latest/api/API_PutMethod.html) or [updating the API method](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateMethod.html) using the API Gateway REST API. In the API Swagger definition, you can set the `operationId` to achieve the same result.

Before showing how to call these methods using an SDK generated by API Gateway for this API, let's recall briefly how to set them up. For detailed instructions, see [Develop REST APIs in API Gateway](rest-api-develop.md). If you're new to API Gateway, see [Choose an AWS Lambda integration tutorial](getting-started-with-lambda-integration.md) first.

## Create models for input and output
<a name="simple-calc-lambda-api-create-models-for-input-and-output"></a>

To specify strongly typed input in the SDK, we create an `Input` model for the API. To describe the response body data type, we create an `Output` model and a `Result` model.

**To create models for the input, output, and result**

1. In the main navigation pane, choose **Models**.

1. Choose **Create model**.

1. For **Name**, enter **input**.

1. For **Content type**, enter **application/json**. 

   If no matching content type is found, request validation is not performed. To use the same model regardless of the content type, enter **\$1default**.

1. For **Model schema**, enter the following model:

   ```
   {
       "$schema" : "$schema": "http://json-schema.org/draft-04/schema#",
       "type":"object",
       "properties":{
           "a":{"type":"number"},
           "b":{"type":"number"},
           "op":{"type":"string"}
       },
       "title":"Input"
   }
   ```

1. Choose **Create model**.

1. Repeat the following steps to create an `Output` model and a `Result` model.

   For the `Output` model, enter the following for the **Model schema**:

   ```
   {
       "$schema": "http://json-schema.org/draft-04/schema#",
       "type": "object",
       "properties": {
           "c": {"type":"number"}
       },
       "title": "Output"
   }
   ```

   For the `Result` model, enter the following for the **Model schema**. Replace the API ID `abc123` with your API ID.

   ```
   {
       "$schema": "http://json-schema.org/draft-04/schema#",
       "type":"object",
       "properties":{
           "input":{
               "$ref":"https://apigateway.amazonaws.com/restapis/abc123/models/Input"
           },
           "output":{
               "$ref":"https://apigateway.amazonaws.com/restapis/abc123/models/Output"
           }
       },
       "title":"Result"
   }
   ```

## Set up GET / method query parameters
<a name="simple-calc-lambda-api-set-up-get-method-query-parameters"></a>

For the `GET /?a=..&b=..&op=..` method, the query parameters are declared in **Method Request**:

**To set up GET / URL query string parameters**

1. In the **Method request** section for the `GET` method on the root (`/`) resource, choose **Edit**.

1. Choose **URL query string parameters** and do the following:

   1. Choose **Add query string**.

   1. For **Name**, enter **a**.

   1. Keep **Required** and **Caching** turned off. 

   1. Keep **Caching** turned off.

   Repeat the same steps and create a query string named **b** and a query string named **op**.

1. Choose **Save**.

## Set up data model for the payload as input to the backend
<a name="simple-calc-lambda-api-set-up-post-method-body-data-type"></a>

For the `POST /` method, we create the `Input` model and add it to the method request to define the shape of input data. 

**To set up the data model for the payload as input to the backend**

1. In the **Method request** section, for the `POST` method on the root (`/`) resource choose **Edit**.

1. Choose **Request body**.

1. Choose **Add model**.

1. For **Content type**, enter **application/json**.

1. For **Model**, select **Input**.

1. Choose **Save**.

With this model, your API customers can call the SDK to specify the input by instantiating an `Input` object. Without this model, your customers would be required to create dictionary object to represent the JSON input to the Lambda function. 

## Set up data model for the result output from the backend
<a name="simple-calc-lambda-api-set-up-all-methods-result-data-type"></a>

For all three methods, we create the `Result` model and add it to the method's `Method Response` to define the shape of output returned by the Lambda function.

**To set up the data model for the result output from the backend**

1. Select the **/\$1a\$1/\$1b\$1/\$1op\$1** resource, and then choose the **GET** method.

1. On the **Method response** tab, under **Response 200**, choose **Edit**.

1. Under **Response body**, choose **Add model**.

1. For **Content type**, enter **application/json**.

1. For **Model**, select **Result**.

1. Choose **Save**.

With this model, your API customers can parse a successful output by reading properties of a `Result` object. Without this model, customers would be required to create dictionary object to represent the JSON output. 

# Simple calculator API OpenAPI definition
<a name="simple-calc-lambda-api-swagger-definition"></a>

The following is the OpenAPI definition of the simple calculator API. You can import it into your account. However, you need to reset the resource-based permissions on the [Lambda function](simple-calc-nodejs-lambda-function.md) after the import. To do so, re-select the Lambda function that you created in your account from the **Integration Request** in the API Gateway console. This will cause the API Gateway console to reset the required permissions. Alternatively, you can use AWS Command Line Interface for Lambda command of [add-permission](https://docs.aws.amazon.com/cli/latest/reference/lambda/add-permission.html).

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

```
{
  "swagger": "2.0",
  "info": {
    "version": "2016-09-29T20:27:30Z",
    "title": "SimpleCalc"
  },
  "host": "t6dve4zn25.execute-api.us-west-2.amazonaws.com",
  "basePath": "/demo",
  "schemes": [
    "https"
  ],
  "paths": {
    "/": {
      "get": {
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "op",
            "in": "query",
            "required": false,
            "type": "string"
          },
          {
            "name": "a",
            "in": "query",
            "required": false,
            "type": "string"
          },
          {
            "name": "b",
            "in": "query",
            "required": false,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Result"
            }
          }
        },
        "x-amazon-apigateway-integration": {
          "requestTemplates": {
            "application/json": "#set($inputRoot = $input.path('$'))\n{\n  \"a\" : $input.params('a'),\n  \"b\" : $input.params('b'),\n  \"op\" : \"$input.params('op')\"\n}"
          },
          "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
          "passthroughBehavior": "when_no_templates",
          "httpMethod": "POST",
          "responses": {
            "default": {
              "statusCode": "200",
              "responseTemplates": {
                "application/json": "#set($inputRoot = $input.path('$'))\n{\n  \"input\" : {\n    \"a\" : $inputRoot.a,\n    \"b\" : $inputRoot.b,\n    \"op\" : \"$inputRoot.op\"\n  },\n  \"output\" : {\n    \"c\" : $inputRoot.c\n  }\n}"
              }
            }
          },
          "type": "aws"
        }
      },
      "post": {
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "in": "body",
            "name": "Input",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Input"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Result"
            }
          }
        },
        "x-amazon-apigateway-integration": {
          "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "POST",
          "responses": {
            "default": {
              "statusCode": "200",
              "responseTemplates": {
                "application/json": "#set($inputRoot = $input.path('$'))\n{\n  \"input\" : {\n    \"a\" : $inputRoot.a,\n    \"b\" : $inputRoot.b,\n    \"op\" : \"$inputRoot.op\"\n  },\n  \"output\" : {\n    \"c\" : $inputRoot.c\n  }\n}"
              }
            }
          },
          "type": "aws"
        }
      }
    },
    "/{a}": {
      "x-amazon-apigateway-any-method": {
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "a",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "404": {
            "description": "404 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "requestTemplates": {
            "application/json": "{\"statusCode\": 200}"
          },
          "passthroughBehavior": "when_no_match",
          "responses": {
            "default": {
              "statusCode": "404",
              "responseTemplates": {
                "application/json": "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }"
              }
            }
          },
          "type": "mock"
        }
      }
    },
    "/{a}/{b}": {
      "x-amazon-apigateway-any-method": {
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "a",
            "in": "path",
            "required": true,
            "type": "string"
          },
          {
            "name": "b",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "404": {
            "description": "404 response"
          }
        },
        "x-amazon-apigateway-integration": {
          "requestTemplates": {
            "application/json": "{\"statusCode\": 200}"
          },
          "passthroughBehavior": "when_no_match",
          "responses": {
            "default": {
              "statusCode": "404",
              "responseTemplates": {
                "application/json": "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }"
              }
            }
          },
          "type": "mock"
        }
      }
    },
    "/{a}/{b}/{op}": {
      "get": {
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "a",
            "in": "path",
            "required": true,
            "type": "string"
          },
          {
            "name": "b",
            "in": "path",
            "required": true,
            "type": "string"
          },
          {
            "name": "op",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Result"
            }
          }
        },
        "x-amazon-apigateway-integration": {
          "requestTemplates": {
            "application/json": "#set($inputRoot = $input.path('$'))\n{\n  \"a\" : $input.params('a'),\n  \"b\" : $input.params('b'),\n  \"op\" : \"$input.params('op')\"\n}"
          },
          "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations",
          "passthroughBehavior": "when_no_templates",
          "httpMethod": "POST",
          "responses": {
            "default": {
              "statusCode": "200",
              "responseTemplates": {
                "application/json": "#set($inputRoot = $input.path('$'))\n{\n  \"input\" : {\n    \"a\" : $inputRoot.a,\n    \"b\" : $inputRoot.b,\n    \"op\" : \"$inputRoot.op\"\n  },\n  \"output\" : {\n    \"c\" : $inputRoot.c\n  }\n}"
              }
            }
          },
          "type": "aws"
        }
      }
    }
  },
  "definitions": {
    "Input": {
      "type": "object",
      "properties": {
        "a": {
          "type": "number"
        },
        "b": {
          "type": "number"
        },
        "op": {
          "type": "string"
        }
      },
      "title": "Input"
    },
    "Output": {
      "type": "object",
      "properties": {
        "c": {
          "type": "number"
        }
      },
      "title": "Output"
    },
    "Result": {
      "type": "object",
      "properties": {
        "input": {
          "$ref": "#/definitions/Input"
        },
        "output": {
          "$ref": "#/definitions/Output"
        }
      },
      "title": "Result"
    }
  }
}
```

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

```
{
  "openapi" : "3.0.1",
  "info" : {
    "title" : "SimpleCalc",
    "version" : "2016-09-29T20:27:30Z"
  },
  "servers" : [ {
    "url" : "https://t6dve4zn25.execute-api.us-west-2.amazonaws.com/{basePath}",
    "variables" : {
      "basePath" : {
        "default" : "demo"
      }
    }
  } ],
  "paths" : {
    "/{a}/{b}" : {
      "x-amazon-apigateway-any-method" : {
        "parameters" : [ {
          "name" : "a",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "b",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "404" : {
            "description" : "404 response",
            "content" : { }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "mock",
          "responses" : {
            "default" : {
              "statusCode" : "404",
              "responseTemplates" : {
                "application/json" : "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }"
              }
            }
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_match"
        }
      }
    },
    "/{a}/{b}/{op}" : {
      "get" : {
        "parameters" : [ {
          "name" : "a",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "b",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "op",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "content" : {
              "application/json" : {
                "schema" : {
                  "$ref" : "#/components/schemas/Result"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "aws",
          "httpMethod" : "POST",
          "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseTemplates" : {
                "application/json" : "#set($inputRoot = $input.path('$'))\n{\n  \"input\" : {\n    \"a\" : $inputRoot.a,\n    \"b\" : $inputRoot.b,\n    \"op\" : \"$inputRoot.op\"\n  },\n  \"output\" : {\n    \"c\" : $inputRoot.c\n  }\n}"
              }
            }
          },
          "requestTemplates" : {
            "application/json" : "#set($inputRoot = $input.path('$'))\n{\n  \"a\" : $input.params('a'),\n  \"b\" : $input.params('b'),\n  \"op\" : \"$input.params('op')\"\n}"
          },
          "passthroughBehavior" : "when_no_templates"
        }
      }
    },
    "/" : {
      "get" : {
        "parameters" : [ {
          "name" : "op",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "a",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        }, {
          "name" : "b",
          "in" : "query",
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "200" : {
            "description" : "200 response",
            "content" : {
              "application/json" : {
                "schema" : {
                  "$ref" : "#/components/schemas/Result"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "aws",
          "httpMethod" : "POST",
          "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseTemplates" : {
                "application/json" : "#set($inputRoot = $input.path('$'))\n{\n  \"input\" : {\n    \"a\" : $inputRoot.a,\n    \"b\" : $inputRoot.b,\n    \"op\" : \"$inputRoot.op\"\n  },\n  \"output\" : {\n    \"c\" : $inputRoot.c\n  }\n}"
              }
            }
          },
          "requestTemplates" : {
            "application/json" : "#set($inputRoot = $input.path('$'))\n{\n  \"a\" : $input.params('a'),\n  \"b\" : $input.params('b'),\n  \"op\" : \"$input.params('op')\"\n}"
          },
          "passthroughBehavior" : "when_no_templates"
        }
      },
      "post" : {
        "requestBody" : {
          "content" : {
            "application/json" : {
              "schema" : {
                "$ref" : "#/components/schemas/Input"
              }
            }
          },
          "required" : true
        },
        "responses" : {
          "200" : {
            "description" : "200 response",
            "content" : {
              "application/json" : {
                "schema" : {
                  "$ref" : "#/components/schemas/Result"
                }
              }
            }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "aws",
          "httpMethod" : "POST",
          "uri" : "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:111122223333:function:Calc/invocations",
          "responses" : {
            "default" : {
              "statusCode" : "200",
              "responseTemplates" : {
                "application/json" : "#set($inputRoot = $input.path('$'))\n{\n  \"input\" : {\n    \"a\" : $inputRoot.a,\n    \"b\" : $inputRoot.b,\n    \"op\" : \"$inputRoot.op\"\n  },\n  \"output\" : {\n    \"c\" : $inputRoot.c\n  }\n}"
              }
            }
          },
          "passthroughBehavior" : "when_no_match"
        }
      }
    },
    "/{a}" : {
      "x-amazon-apigateway-any-method" : {
        "parameters" : [ {
          "name" : "a",
          "in" : "path",
          "required" : true,
          "schema" : {
            "type" : "string"
          }
        } ],
        "responses" : {
          "404" : {
            "description" : "404 response",
            "content" : { }
          }
        },
        "x-amazon-apigateway-integration" : {
          "type" : "mock",
          "responses" : {
            "default" : {
              "statusCode" : "404",
              "responseTemplates" : {
                "application/json" : "{ \"Message\" : \"Can't $context.httpMethod $context.resourcePath\" }"
              }
            }
          },
          "requestTemplates" : {
            "application/json" : "{\"statusCode\": 200}"
          },
          "passthroughBehavior" : "when_no_match"
        }
      }
    }
  },
  "components" : {
    "schemas" : {
      "Input" : {
        "title" : "Input",
        "type" : "object",
        "properties" : {
          "a" : {
            "type" : "number"
          },
          "b" : {
            "type" : "number"
          },
          "op" : {
            "type" : "string"
          }
        }
      },
      "Output" : {
        "title" : "Output",
        "type" : "object",
        "properties" : {
          "c" : {
            "type" : "number"
          }
        }
      },
      "Result" : {
        "title" : "Result",
        "type" : "object",
        "properties" : {
          "input" : {
            "$ref" : "#/components/schemas/Input"
          },
          "output" : {
            "$ref" : "#/components/schemas/Output"
          }
        }
      }
    }
  }
}
```

------

# Generate the Java SDK of an API in API Gateway
<a name="generate-java-sdk-of-an-api"></a>

The following procedure shows how to generate the Java SDK of an API in API Gateway.

**To generate the Java SDK of an API in API Gateway**

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

1. Choose a REST API.

1. Choose **Stages**. 

1. In the **Stages** pane, select the name of the stage.

1. Open the **Stage actions** menu, and then choose **Generate SDK**.

1. For **Platform**, choose the **Java** platform and do the following:

   1.  For **Service Name**, specify the name of your SDK. For example, **SimpleCalcSdk**. This becomes the name of your SDK client class. The name corresponds to the `<name>` tag under `<project>` in the pom.xml file, which is in the SDK's project folder. Do not include hyphens.

   1.  For **Java Package Name**, specify a package name for your SDK. For example, **examples.aws.apig.simpleCalc.sdk**. This package name is used as the namespace of your SDK library. Do not include hyphens.

   1.  For **Java Build System**, enter **maven** or **gradle** to specify the build system.

   1.  For **Java Group Id**, enter a group identifier for your SDK project. For example, enter **my-apig-api-examples**. This identifier corresponds to the `<groupId>` tag under `<project>` in the `pom.xml` file, which is in the SDK's project folder.

   1.  For **Java Artifact Id**, enter an artifact identifier for your SDK project. For example, enter **simple-calc-sdk**. This identifier corresponds to the `<artifactId>` tag under `<project>` in the `pom.xml` file, which is in the SDK's project folder.

   1.  For **Java Artifact Version**, enter a version identifier string. For example, **1.0.0**. This version identifier corresponds to the `<version>` tag under `<project>` in the `pom.xml` file, which is in the SDK's project folder.

   1. For **Source Code License Text**, enter the license text of your source code, if any.

1. Choose **Generate SDK**, and then follow the on-screen directions to download the SDK generated by API Gateway.

Follow the instructions in [Use a Java SDK generated by API Gateway for a REST API](how-to-call-apigateway-generated-java-sdk.md) to use the generated SDK.

 Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. 

# Generate the Android SDK of an API in API Gateway
<a name="generate-android-sdk-of-an-api"></a>

The following procedure shows how to generate the Android SDK of an API in API Gateway.

**To generate the Android SDK of an API in API Gateway**

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

1. Choose a REST API.

1. Choose **Stages**. 

1. In the **Stages** pane, select the name of the stage.

1. Open the **Stage actions** menu, and then choose **Generate SDK**.

1. For **Platform**, choose the Android platform and do the following: 

   1.  For **Group ID**, enter the unique identifier for the corresponding project. This is used in the `pom.xml` file (for example, **com.mycompany**).

   1.  For **Invoker package**, enter the namespace for the generated client classes (for example, **com.mycompany.clientsdk**).

   1.  For **Artifact ID**, enter the name of the compiled .jar file without the version. This is used in the `pom.xml` file (for example, **aws-apigateway-api-sdk**).

   1. For **Artifact version**, enter the artifact version number for the generated client. This is used in the `pom.xml` file and should follow a *major*.*minor*.*patch* pattern (for example, **1.0.0**).

1. Choose **Generate SDK**, and then follow the on-screen directions to download the SDK generated by API Gateway.

Follow the instructions in [Use an Android SDK generated by API Gateway for a REST API](how-to-generate-sdk-android.md) to use the generated SDK. 

 Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. 

# Generate the iOS SDK of an API in API Gateway
<a name="generate-ios-sdk-of-an-api"></a>

The following procedure shows how to generate the iOS SDK of an API in API Gateway.

**To generate the iOS SDK of an API in API Gateway**

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

1. Choose a REST API.

1. Choose **Stages**. 

1. In the **Stages** pane, select the name of the stage.

1. Open the **Stage actions** menu, and then choose **Generate SDK**.

1. For **Platform**, choose the **iOS (Objective-C) or iOS (Swift)** platform and do the following: 

   1. Type a unique prefix in the **Prefix** box.

     The effect of prefix is as follows: if you assign, for example, **SIMPLE\$1CALC** as the prefix for the SDK of the [SimpleCalc](simple-calc-lambda-api.md) API with `input`, `output`, and `result` models, the generated SDK will contain the `SIMPLE_CALCSimpleCalcClient` class that encapsulates the API, including the method requests/responses. In addition, the generated SDK will contain the `SIMPLE_CALCinput`, `SIMPLE_CALCoutput`, and `SIMPLE_CALCresult` classes to represent the input, output, and results, respectively, to represent the request input and response output. For more information, see [Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift](how-to-generate-sdk-ios.md). 

1. Choose **Generate SDK**, and then follow the on-screen directions to download the SDK generated by API Gateway.

Follow the instructions in [Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift](how-to-generate-sdk-ios.md) to use the generated SDK.

 Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. 

# Generate the JavaScript SDK of a REST API in API Gateway
<a name="generate-javascript-sdk-of-an-api"></a>

The following procedure shows how to generate the JaveScript SDK of an API in API Gateway.

**To generate the JavaScript SDK of an API in API Gateway**

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

1. Choose a REST API.

1. Choose **Stages**. 

1. In the **Stages** pane, select the name of the stage.

1. Open the **Stage actions** menu, and then choose **Generate SDK**.

1. For **Platform**, choose the **JavaScript** platform. 

1. Choose **Generate SDK**, and then follow the on-screen directions to download the SDK generated by API Gateway.

Follow the instructions in [Use a JavaScript SDK generated by API Gateway for a REST API](how-to-generate-sdk-javascript.md) to use the generated SDK.

 Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. 

# Generate the Ruby SDK of an API in API Gateway
<a name="generate-ruby-sdk-of-an-api"></a>

The following procedure shows how to generate the Ruby SDK of an API in API Gateway.

**To generate the Ruby SDK of an API in API Gateway**

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

1. Choose a REST API.

1. Choose **Stages**. 

1. In the **Stages** pane, select the name of the stage.

1. Open the **Stage actions** menu, and then choose **Generate SDK**.

1. For **Platform**, choose the **Ruby** platform and do the following: 

   1.  For **Service Name**, specify the name of your SDK. For example, **SimpleCalc**. This is used to generate the Ruby Gem namespace of your API. The name must be all letters, (`a-zA-Z`), without any other special characters or numbers.

   1.  For **Ruby Gem Name**, specify the name of the Ruby Gem to contain the generated SDK source code for your API. By default, it is the lower-cased service name plus the `-sdk` suffix—for example, **simplecalc-sdk**.

   1.  For **Ruby Gem Version**, specify a version number for the generated Ruby Gem. By default, it is set to `1.0.0`.

1. Choose **Generate SDK**, and then follow the on-screen directions to download the SDK generated by API Gateway.

Follow the instructions in [Use a Ruby SDK generated by API Gateway for a REST API](how-to-call-sdk-ruby.md) to use the generated SDK.

 Every time you update an API, you must redeploy the API and regenerate the SDK to have the updates included. 

# Generate SDKs for an API using AWS CLI commands in API Gateway
<a name="how-to-generate-sdk-cli"></a>

You can use AWS CLI to generate and download an SDK of an API for a supported platform by calling the [get-sdk](https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-sdk.html) command. We demonstrate this for some of the supported platforms in the following.

**Topics**
+ [Generate and download the Java for Android SDK using the AWS CLI](#how-to-generate-sdk-cli-android)
+ [Generate and download the JavaScript SDK using the AWS CLI](#how-to-generate-sdk-cli-js)
+ [Generate and download the Ruby SDK using the AWS CLI](#how-to-generate-sdk-cli-ruby)

## Generate and download the Java for Android SDK using the AWS CLI
<a name="how-to-generate-sdk-cli-android"></a>

To generate and download a Java for Android SDK generated by API Gateway of an API (`udpuvvzbkc`) at a given stage (`test`), call the command as follows:

```
aws apigateway get-sdk \
            --rest-api-id udpuvvzbkc \
            --stage-name test \
            --sdk-type android \
            --parameters groupId='com.mycompany',\
                invokerPackage='com.mycompany.myApiSdk',\ 
                artifactId='myApiSdk',\
                artifactVersion='0.0.1' \
            ~/apps/myApi/myApi-android-sdk.zip
```

The last input of `~/apps/myApi/myApi-android-sdk.zip` is the path to the downloaded SDK file named `myApi-android-sdk.zip`.

## Generate and download the JavaScript SDK using the AWS CLI
<a name="how-to-generate-sdk-cli-js"></a>

To generate and download a JavaScript SDK generated by API Gateway of an API (`udpuvvzbkc`) at a given stage (`test`), call the command as follows:

```
aws apigateway get-sdk \
            --rest-api-id udpuvvzbkc \
            --stage-name test \
            --sdk-type javascript \
            ~/apps/myApi/myApi-js-sdk.zip
```

The last input of `~/apps/myApi/myApi-js-sdk.zip` is the path to the downloaded SDK file named `myApi-js-sdk.zip`.

## Generate and download the Ruby SDK using the AWS CLI
<a name="how-to-generate-sdk-cli-ruby"></a>

To generate and download a Ruby SDK of an API (`udpuvvzbkc`) at a given stage (`test`), call the command as follows:

```
aws apigateway get-sdk \
            --rest-api-id udpuvvzbkc \
            --stage-name test  \
            --sdk-type ruby \
            --parameters service.name=myApiRubySdk,ruby.gem-name=myApi,ruby.gem-version=0.01 \
            ~/apps/myApi/myApi-ruby-sdk.zip
```

The last input of `~/apps/myApi/myApi-ruby-sdk.zip` is the path to the downloaded SDK file named `myApi-ruby-sdk.zip`.

 Next, we show how to use the generated SDK to call the underlying API. For more information, see [Invoke REST APIs in API Gateway](how-to-call-api.md). 

# Sell your API Gateway APIs through AWS Marketplace
<a name="sell-api-as-saas-on-aws-marketplace"></a>

After you build, test, and deploy your APIs, you can package them in an API Gateway [usage plan](api-gateway-api-usage-plans.md) and sell the plan as a Software as a Service (SaaS) product through AWS Marketplace. API buyers subscribing to your product offering are billed by AWS Marketplace based on the number of requests made to the usage plan.

To sell your APIs on AWS Marketplace, you must set up the sales channel to integrate AWS Marketplace with API Gateway. Generally speaking, this involves listing your product on AWS Marketplace, setting up an IAM role with appropriate policies to allow API Gateway to send usage metrics to AWS Marketplace, associating an AWS Marketplace product with an API Gateway usage plan, and associating an AWS Marketplace buyer with an API Gateway API key. Details are discussed in the following sections.

For more information about selling your API as a SaaS product on AWS Marketplace, see the [AWS Marketplace User Guide](https://docs.aws.amazon.com/marketplace/latest/userguide/).

**Topics**
+ [Initialize AWS Marketplace integration with API Gateway](#sell-api-as-saas-on-aws-marketplace-initial-setup)
+ [Handle customer subscription to usage plans](#sell-api-as-saas-on-aws-marketplace-subscription-unsubscription)

## Initialize AWS Marketplace integration with API Gateway
<a name="sell-api-as-saas-on-aws-marketplace-initial-setup"></a>

The following tasks are for one-time initialization of AWS Marketplace integration with API Gateway, which enables you to sell your APIs as a SaaS product.

### List a product on AWS Marketplace
<a name="sell-api-as-saas-on-aws-marketplace-inital-setup-list-product"></a>

To list your usage plan as a SaaS product, submit a product load form through [AWS Marketplace](https://aws.amazon.com/marketplace/partners/management-tour). The product must contain a dimension named `apigateway` of the `requests` type. This dimension defines the price-per-request and is used by API Gateway to meter requests to your APIs.

### Create the metering role
<a name="sell-api-as-saas-on-aws-marketplace-inital-setup-create-metering-role"></a>

Create an IAM role named `ApiGatewayMarketplaceMeteringRole` with the following execution policy and trust policy. This role allows API Gateway to send usage metrics to AWS Marketplace on your behalf.

#### Execution policy of the metering role
<a name="sell-api-as-saas-on-aws-marketplace-inital-setup-create-metering-role-execution-policy"></a>

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "aws-marketplace:BatchMeterUsage",
        "aws-marketplace:ResolveCustomer"
      ],
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}
```

------

#### Trusted relationship policy of the metering role
<a name="sell-api-as-saas-on-aws-marketplace-inital-setup-create-metering-role-trusted-policy"></a>

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

### Associate usage plan with AWS Marketplace product
<a name="sell-api-as-saas-on-aws-marketplace-associate-usage-plan-with-saas-product"></a>

When you list a product on AWS Marketplace, you receive an AWS Marketplace product code. To integrate API Gateway with AWS Marketplace, associate your usage plan with the AWS Marketplace product code. You enable the association by setting the API Gateway `UsagePlan`'s [https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlan.html#productCode](https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlan.html#productCode) field to your AWS Marketplace product code, using the API Gateway console, the API Gateway REST API, the AWS CLI for API Gateway, or AWS SDK for API Gateway. The following code example uses the API Gateway REST API:

```
PATCH /usageplans/USAGE_PLAN_ID
Host: apigateway.region.amazonaws.com
Authorization: ...

{
    "patchOperations" : [{
        "path" : "/productCode",
        "value" : "MARKETPLACE_PRODUCT_CODE",
        "op" : "replace"
    }]
}
```

## Handle customer subscription to usage plans
<a name="sell-api-as-saas-on-aws-marketplace-subscription-unsubscription"></a>

The following tasks are handled by your developer portal application.

When a customer subscribes to your product through AWS Marketplace, AWS Marketplace forwards a `POST` request to the SaaS subscriptions URL that you registered when listing your product on AWS Marketplace. The `POST` request comes with an `x-amzn-marketplace-token` parameter containing buyer information. Follow the instructions in [SaaS customer onboarding](https://docs.aws.amazon.com/marketplace/latest/userguide/saas-product-customer-setup.html#in-your-application) to handle this redirect in your developer portal application.

Responding to a customer's subscribing request, AWS Marketplace sends a `subscribe-success` notification to an Amazon SNS topic that you can subscribe to. (See [SaaS customer onboarding](https://docs.aws.amazon.com/marketplace/latest/userguide/saas-product-customer-setup.html#in-your-application)). To accept the customer subscription request, you handle the `subscribe-success` notification by creating or retrieving an API Gateway API key for the customer, associating the customer's AWS Marketplace-provisioned `customerId` with the API keys, and then adding the API key to your usage plan.

When the customer's subscription request completes, the developer portal application should present the customer with the associated API key and inform the customer that the API key must be included in the `x-api-key` header in requests to the APIs.

When a customer cancels a subscription to a usage plan, AWS Marketplace sends an `unsubscribe-success` notification to the SNS topic. To complete the process of unsubscribing the customer, you handle the `unsubscribe-success` notification by removing the customer's API keys from the usage plan.

### Authorize a customer to access a usage plan
<a name="sell-api-as-saas-on-aws-marketplace-subscription-unsubscription-authorize-access-to-usage-plan"></a>

To authorize access to your usage plan for a given customer, use the API Gateway API to fetch or create an API key for the customer and add the API key to the usage plan. 

The following example shows how to call the API Gateway REST API to create a new API key with a specific AWS Marketplace `customerId` value (*MARKETPLACE\$1CUSTOMER\$1ID*).

```
POST apikeys HTTP/1.1
Host: apigateway.region.amazonaws.com
Authorization: ...

{
  "name" : "my_api_key",
  "description" : "My API key",
  "enabled" : "false",
  "stageKeys" : [ {
    "restApiId" : "uycll6xg9a",
    "stageName" : "prod"
  } ],
  "customerId" : "MARKETPLACE_CUSTOMER_ID"
}
```

The following example shows how to get an API key with a specific AWS Marketplace `customerId` value (*MARKETPLACE\$1CUSTOMER\$1ID*).

```
GET apikeys?customerId=MARKETPLACE_CUSTOMER_ID HTTP/1.1
Host: apigateway.region.amazonaws.com
Authorization: ...
```

To add an API key to a usage plan, create a [https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlanKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UsagePlanKey.html) with the API key for the relevant usage plan. The following example shows how to accomplish this using the API Gateway REST API, where `n371pt` is the usage plan ID and `q5ugs7qjjh` is an example API `keyId` returned from the preceding examples.

```
POST /usageplans/n371pt/keys HTTP/1.1
Host: apigateway.region.amazonaws.com
Authorization: ...

{
    "keyId": "q5ugs7qjjh",
    "keyType": "API_KEY"
}
```

### Associate a customer with an API key
<a name="sell-api-as-saas-on-aws-marketplace-subscription-unsubscription-associate-marketplace"></a>

You must update the [https://docs.aws.amazon.com/apigateway/latest/api/API_ApiKey.html](https://docs.aws.amazon.com/apigateway/latest/api/API_ApiKey.html)'s `customerId` field to the AWS Marketplace customer ID of the customer. This associates the API key with the AWS Marketplace customer, which enables metering and billing for the buyer. The following code example calls the API Gateway REST API to do that.

```
PATCH /apikeys/q5ugs7qjjh
Host: apigateway.region.amazonaws.com
Authorization: ...
        
{
    "patchOperations" : [{
        "path" : "/customerId",
        "value" : "MARKETPLACE_CUSTOMER_ID",
        "op" : "replace"
    }]
}
```