

# Invoke REST APIs in API Gateway
Invoke

To call a deployed API, clients submit requests to the URL for the API Gateway component service for API execution, known as `execute-api`.

The base URL for REST APIs is in the following format: 

```
https://api-id.execute-api.region.amazonaws.com/stage/
```

where *api-id* is the API identifier, *region* is the AWS Region, and *stage* is the stage name of the API deployment. 

**Important**  
Before you can invoke an API, you must deploy it in API Gateway. For instructions on deploying an API, see [Deploy REST APIs in API Gateway](how-to-deploy-api.md). 

**Topics**
+ [

## Obtaining an API's invoke URL
](#apigateway-how-to-call-rest-api)
+ [

## Invoking an API
](#apigateway-call-api)
+ [

# Use the API Gateway console to test a REST API method
](how-to-test-method.md)
+ [

# Use a Java SDK generated by API Gateway for a REST API
](how-to-call-apigateway-generated-java-sdk.md)
+ [

# Use an Android SDK generated by API Gateway for a REST API
](how-to-generate-sdk-android.md)
+ [

# Use a JavaScript SDK generated by API Gateway for a REST API
](how-to-generate-sdk-javascript.md)
+ [

# Use a Ruby SDK generated by API Gateway for a REST API
](how-to-call-sdk-ruby.md)
+ [

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

## Obtaining an API's invoke URL


You can use the console, the AWS CLI, or an exported OpenAPI definition to obtain an API's invoke URL.

### Obtaining an API's invoke URL using the console


The following procedure shows how to obtain an API's invoke URL in the REST API console.

**To obtain an API's invoke URL using the REST API console**

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

1. Choose a deployed API.

1. From the main navigation pane, choose **Stage**.

1. Under **Stage details**, choose the copy icon to copy your API's invoke URL.

   This URL is for the root resource of your API.  
![\[After you create your REST API, the console shows your API's invoke URL.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/getting-started-rest-invoke-url.png)

1. To obtain an API's invoke URL for another resource in your API, expand the stage under the secondary navigation pane, and then choose a method.

1. Choose the copy icon to copy your API's resource-level invoke URL.  
![\[The resource-level URL for your REST API is under the secondary navigation pane of the stage.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/resource-level-invoke-url.png)

#### Obtaining an API's invoke URL using the AWS CLI


The following procedure shows how to obtain an API's invoke URL using the AWS CLI.

**To obtain an API's invoke URL using the AWS CLI**

1. Use the following command to obtain the `rest-api-id`. This command returns all `rest-api-id` values in your Region. For more information, see [get-rest-apis](https://docs.aws.amazon.com/cli/latest/reference/apigateway/get-rest-apis.html).

   ```
   aws apigateway get-rest-apis
   ```

1. Replace the example `rest-api-id` with your `rest-api-id`, replace the example *\$1stage-name\$1* with your *\$1stage-name\$1*, and replace the *\$1region\$1*, with your Region.

   ```
   https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage_name}/
   ```

##### Obtaining an API's invoke URL using the exported OpenAPI definition file of the API


You can also construct the root URL by combining the `host` and `basePath` fields of an exported OpenAPI definition file of the API. For instructions on how to export your API, see [Export a REST API from API Gateway](api-gateway-export-api.md).

## Invoking an API


You can call your deployed API using the browser, curl, or other applications, like [Postman](https://www.postman.com/).

Additionally, you can use the API Gateway console to test an API call. Test uses the API Gateway's `TestInvoke` feature, which allows API testing before the API is deployed. For more information, see [Use the API Gateway console to test a REST API method](how-to-test-method.md).

**Note**  
Query string parameter values in an invocation URL cannot contain `%%`.

### Invoking an API using a web browser


If your API permits anonymous access, you can use any web browser to invoke any `GET` method. Enter the complete invocation URL in the browser's address bar.

For other methods or any authentication-required calls, you must specify a payload or sign the requests. You can handle these in a script behind an HTML page or in a client application using one of the AWS SDKs.

#### Invoking an API using curl


You can use a tool like [curl](https://curl.se/) in your terminal to call your API. The following example curl command invokes the GET method on the `getUsers` resource of the `prod` stage of an API.

------
#### [ Linux or Macintosh ]

```
curl -X GET 'https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers'
```

------
#### [ Windows ]

```
curl -X GET "https://b123abcde4.execute-api.us-west-2.amazonaws.com/prod/getUsers"
```

------

# Use the API Gateway console to test a REST API method
Use the console to test a REST API method

Use the API Gateway console to test a REST API method.

**Topics**
+ [

## Prerequisites
](#how-to-test-method-prerequisites)
+ [

## Test a method with the API Gateway console
](#how-to-test-method-console)

## Prerequisites

+ You must specify the settings for the methods you want to test. Follow the instructions in [Methods for REST APIs in API Gateway](how-to-method-settings.md).

## Test a method with the API Gateway console


**Important**  
Testing methods with the API Gateway console might result in changes to resources that cannot be undone. Testing a method with the API Gateway console is the same as calling the method outside of the API Gateway console. For example, if you use the API Gateway console to call a method that deletes an API's resources, if the method call is successful, the API's resources will be deleted.

**To test a method**

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 **Resources** pane, choose the method you want to test.

1. Choose the **Test** tab. You might need to choose the right arrow button to show the tab.  
![\[Use the test tab to test your API. It is next to the method response tab.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/api-gateway-test-new-console.png)

    Enter values in any of the displayed boxes (such as **Query strings**, **Headers**, and **Request body**). The console includes these values in the method request in default application/json form.

   For additional options you might need to specify, contact the API owner.

1. Choose **Test**. The following information will be displayed:
   + **Request** is the resource's path that was called for the method.
   + **Status** is the response's HTTP status code.
   + **Latency (ms)** is the time between the receipt of the request from the caller and the returned response.
   + **Response body** is the HTTP response body.
   + **Response headers** are the HTTP response headers.
**Tip**  
Depending on the mapping, the HTTP status code, response body, and response headers might be different from those sent from the Lambda function, HTTP proxy, or AWS service proxy.
   + **Logs** are the simulated Amazon CloudWatch Logs entries that would have been written if this method were called outside of the API Gateway console.
**Note**  
Although the CloudWatch Logs entries are simulated, the results of the method call are real.

 In addition to using the API Gateway console, you can use AWS CLI or an AWS SDK for API Gateway to test invoking a method. To do so using AWS CLI, see [test-invoke-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/test-invoke-method.html). 

# Use a Java SDK generated by API Gateway for a REST API


In this section, we outline the steps to use a Java SDK generated by API Gateway for a REST API, by using the [Simple Calculator](simple-calc-lambda-api-swagger-definition.md) API as an example. Before proceeding, you must complete the steps in [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md). 

**To install and use a Java SDK generated by API Gateway**

1. Extract the contents of the API Gateway-generated .zip file that you downloaded earlier.

1. Download and install [Apache Maven](https://maven.apache.org/) (must be version 3.5 or later).

1. Download and install [JDK 8](https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html).

1. Set the `JAVA_HOME` environment variable.

1.  Go to the unzipped SDK folder where the pom.xml file is located. This folder is `generated-code` by default. Run the **mvn install** command to install the compiled artifact files to your local Maven repository. This creates a `target` folder containing the compiled SDK library. 

1.  Type the following command in an empty directory to create a client project stub to call the API using the installed SDK library. 

   ```
   mvn -B archetype:generate \
       -DarchetypeGroupdId=org.apache.maven.archetypes \
       -DgroupId=examples.aws.apig.simpleCalc.sdk.app \
       -DartifactId=SimpleCalc-sdkClient
   ```
**Note**  
 The separator `\` in the preceding command is included for readability. The whole command should be on a single line without the separator. 

    This command creates an application stub. The application stub contains a `pom.xml` file and an `src` folder under the project's root directory (*SimpleCalc-sdkClient* in the preceding command). Initially, there are two source files: `src/main/java/{package-path}/App.java` and `src/test/java/{package-path}/AppTest.java`. In this example, *\$1package-path\$1* is `examples/aws/apig/simpleCalc/sdk/app`. This package path is derived from the `DarchetypeGroupdId` value. You can use the `App.java` file as a template for your client application, and you can add others in the same folder if needed. You can use the `AppTest.java` file as a unit test template for your application, and you can add other test code files to the same test folder as needed. 

1. Update the package dependencies in the generated `pom.xml` file to the following, substituting your project's `groupId`, `artifactId`, `version`, and `name` properties, if necessary:

   ```
   <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>examples.aws.apig.simpleCalc.sdk.app</groupId>
     <artifactId>SimpleCalc-sdkClient</artifactId>
     <packaging>jar</packaging>
     <version>1.0-SNAPSHOT</version>
     <name>SimpleCalc-sdkClient</name>
     <url>http://maven.apache.org</url>
   
      <dependencies>
         <dependency>
             <groupId>com.amazonaws</groupId>
             <artifactId>aws-java-sdk-core</artifactId>
             <version>1.11.94</version>
         </dependency>
         <dependency>
             <groupId>my-apig-api-examples</groupId>
             <artifactId>simple-calc-sdk</artifactId>
             <version>1.0.0</version>
         </dependency>
         
       <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
         <scope>test</scope>
       </dependency>
   
       <dependency>
           <groupId>commons-io</groupId>
           <artifactId>commons-io</artifactId>
           <version>2.5</version>
       </dependency>    
     </dependencies>
   
     <build>
       <plugins>
         <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>3.5.1</version>
           <configuration>
             <source>1.8</source>
             <target>1.8</target>
           </configuration>
         </plugin>
       </plugins>
     </build>
   </project>
   ```
**Note**  
 When a newer version of dependent artifact of `aws-java-sdk-core` is incompatible with the version specified above (`1.11.94`), you must update the `<version>` tag to the new version.

1.  Next, we show how to call the API using the SDK by calling the `getABOp(GetABOpRequest req)`, `getApiRoot(GetApiRootRequest req)`, and `postApiRoot(PostApiRootRequest req)` methods of the SDK. These methods correspond to the `GET /{a}/{b}/{op}`, `GET /?a={x}&b={y}&op={operator}`, and `POST /` methods, with a payload of `{"a": x, "b": y, "op": "operator"}` API requests, respectively. 

    Update the `App.java` file as follows: 

   ```
   package examples.aws.apig.simpleCalc.sdk.app;
   
   import java.io.IOException;
   
   import com.amazonaws.opensdk.config.ConnectionConfiguration;
   import com.amazonaws.opensdk.config.TimeoutConfiguration;
   
   import examples.aws.apig.simpleCalc.sdk.*;
   import examples.aws.apig.simpleCalc.sdk.model.*;
   import examples.aws.apig.simpleCalc.sdk.SimpleCalcSdk.*;
   
   public class App 
   {
       SimpleCalcSdk sdkClient;
   
       public App() {
           initSdk();
       }
   
       // The configuration settings are for illustration purposes and may not be a recommended best practice.
       private void initSdk() {
           sdkClient = SimpleCalcSdk.builder()
                 .connectionConfiguration(
                     new ConnectionConfiguration()
                           .maxConnections(100)
                           .connectionMaxIdleMillis(1000))
                 .timeoutConfiguration(
                     new TimeoutConfiguration()
                           .httpRequestTimeout(3000)
                           .totalExecutionTimeout(10000)
                           .socketTimeout(2000))
           .build();
   
       }
       // Calling shutdown is not necessary unless you want to exert explicit control of this resource.
       public void shutdown() {
           sdkClient.shutdown();
       }
        
       // GetABOpResult getABOp(GetABOpRequest getABOpRequest)
       public Output getResultWithPathParameters(String x, String y, String operator) {
       	operator = operator.equals("+") ? "add" : operator;
       	operator = operator.equals("/") ? "div" : operator; 
   
           GetABOpResult abopResult = sdkClient.getABOp(new GetABOpRequest().a(x).b(y).op(operator));
           return abopResult.getResult().getOutput();
       }
   
       public Output getResultWithQueryParameters(String a, String b, String op) {
           GetApiRootResult rootResult = sdkClient.getApiRoot(new GetApiRootRequest().a(a).b(b).op(op));
           return rootResult.getResult().getOutput();
       }
   
       public Output getResultByPostInputBody(Double x, Double y, String o) {
       	PostApiRootResult postResult = sdkClient.postApiRoot(
       		new PostApiRootRequest().input(new Input().a(x).b(y).op(o)));
       	return postResult.getResult().getOutput();
       }
   
       public static void main( String[] args )
       {
           System.out.println( "Simple calc" );
           // to begin
           App calc = new App();
           
           // call the SimpleCalc API
           Output res = calc.getResultWithPathParameters("1", "2", "-");
           System.out.printf("GET /1/2/-: %s\n", res.getC());
   
           // Use the type query parameter
           res = calc.getResultWithQueryParameters("1", "2", "+");
           System.out.printf("GET /?a=1&b=2&op=+: %s\n", res.getC());
   
           // Call POST with an Input body.
           res = calc.getResultByPostInputBody(1.0, 2.0, "*");
           System.out.printf("PUT /\n\n{\"a\":1, \"b\":2,\"op\":\"*\"}\n %s\n", res.getC());
   
           
       }
   }
   ```

    In the preceding example, the configuration settings used to instantiate the SDK client are for illustration purposes and are not necessarily recommended best practice. Also, calling `sdkClient.shutdown()` is optional, especially if you need precise control on when to free up resources. 

 We have shown the essential patterns to call an API using a Java SDK. You can extend the instructions to calling other API methods. 

# Use an Android SDK generated by API Gateway for a REST API


In this section, we will outline the steps to use an Android SDK generated by API Gateway for a REST API. Before proceeding further, you must have already completed the steps in [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md).

**Note**  
 The generated SDK is not compatible with Android 4.4 and earlier. For more information, see [Amazon API Gateway important notes](api-gateway-known-issues.md). 

**To install and use an Android SDK generated by API Gateway**

1. Extract the contents of the API Gateway-generated .zip file that you downloaded earlier.

1. Download and install [Apache Maven](https://maven.apache.org/) (preferably version 3.x).

1. Download and install [JDK 8](https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html).

1. Set the `JAVA_HOME` environment variable.

1. Run the **mvn install** command to install the compiled artifact files to your local Maven repository. This creates a `target` folder containing the compiled SDK library.

1. Copy the SDK file (the name of which is derived from the **Artifact Id** and **Artifact Version** you specified when generating the SDK, e.g., `simple-calcsdk-1.0.0.jar`) from the `target` folder, along with all of the other libraries from the `target/lib` folder, into your project's `lib` folder.

   If you use Android Studio, create a `libs` folder under your client app module and copy the required .jar file into this folder. Verify that the dependencies section in the module's gradle file contains the following.

   ```
       compile fileTree(include: ['*.jar'], dir: 'libs')
       compile fileTree(include: ['*.jar'], dir: 'app/libs')
   ```

   Make sure no duplicated .jar files are declared.

1. Use the `ApiClientFactory` class to initialize the API Gateway-generated SDK. For example:

   ```
   ApiClientFactory factory = new ApiClientFactory();
   
   // Create an instance of your SDK. Here, 'SimpleCalcClient.java' is the compiled java class for the SDK generated by API Gateway. 
   final SimpleCalcClient client = factory.build(SimpleCalcClient.class);
   
   // Invoke a method: 
   //   For the 'GET /?a=1&b=2&op=+' method exposed by the API, you can invoke it by calling the following SDK method:
   
   Result output = client.rootGet("1", "2", "+");
   
   //     where the Result class of the SDK corresponds to the Result model of the API.
   //
   
   //   For the 'GET /{a}/{b}/{op}'  method exposed by the API, you can call the following SDK method to invoke the request,
   
   Result output = client.aBOpGet(a, b, c);
   
   //     where a, b, c can be "1", "2", "add", respectively.
   
   //   For the following API method:
   //        POST /
   //        host: ...
   //        Content-Type: application/json
   //    
   //        { "a": 1, "b": 2, "op": "+" }
   // you can call invoke it by calling the rootPost method of the SDK as follows:
   Input body = new Input();
   input.a=1;
   input.b=2;
   input.op="+";
   Result output = client.rootPost(body);
   
   //      where the Input class of the SDK corresponds to the Input model of the API.
   
   // Parse the result:
   //     If the 'Result' object is { "a": 1, "b": 2, "op": "add", "c":3"}, you retrieve the result 'c') as 
   
   String result=output.c;
   ```

1. To use an Amazon Cognito credentials provider to authorize calls to your API, use the `ApiClientFactory` class to pass a set of AWS credentials by using the SDK generated by API Gateway, as shown in the following example.

   ```
   // Use CognitoCachingCredentialsProvider to provide AWS credentials
   // for the ApiClientFactory
   AWSCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
           context,          // activity context
           "identityPoolId", // Cognito identity pool id
           Regions.US_EAST_1 // region of Cognito identity pool
   );
   
   ApiClientFactory factory = new ApiClientFactory()
     .credentialsProvider(credentialsProvider);
   ```

1. To set an API key by using the API Gateway- generated SDK, use code similar to the following.

   ```
   ApiClientFactory factory = new ApiClientFactory()
     .apiKey("YOUR_API_KEY");
   ```

# Use a JavaScript SDK generated by API Gateway for a REST API


The following procedure shows how to use a JavaScript SDK generated by API Gateway.

**Note**  
These instructions assume you have already completed the instructions in [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md).

**Important**  
If your API only has ANY methods defined, the generated SDK package will not contain an `apigClient.js` file, and you will need to define the ANY methods yourself.

**To install, initiate and call a JavaScript SDK generated by API Gateway for a REST API**

1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier.

1. Enable cross-origin resource sharing (CORS) for all of the methods the SDK generated by API Gateway will call. For instructions, see [CORS for REST APIs in API Gateway](how-to-cors.md).

1. In your web page, include references to the following scripts.

   ```
   <script type="text/javascript" src="lib/axios/dist/axios.standalone.js"></script>
   <script type="text/javascript" src="lib/CryptoJS/rollups/hmac-sha256.js"></script>
   <script type="text/javascript" src="lib/CryptoJS/rollups/sha256.js"></script>
   <script type="text/javascript" src="lib/CryptoJS/components/hmac.js"></script>
   <script type="text/javascript" src="lib/CryptoJS/components/enc-base64.js"></script>
   <script type="text/javascript" src="lib/url-template/url-template.js"></script>
   <script type="text/javascript" src="lib/apiGatewayCore/sigV4Client.js"></script>
   <script type="text/javascript" src="lib/apiGatewayCore/apiGatewayClient.js"></script>
   <script type="text/javascript" src="lib/apiGatewayCore/simpleHttpClient.js"></script>
   <script type="text/javascript" src="lib/apiGatewayCore/utils.js"></script>
   <script type="text/javascript" src="apigClient.js"></script>
   ```

1. In your code, initialize the SDK generated by API Gateway by using code similar to the following.

   ```
   var apigClient = apigClientFactory.newClient();
   ```

   To initialize the SDK generated by API Gateway with AWS credentials, use code similar to the following. If you use AWS credentials, all requests to the API will be signed. 

   ```
   var apigClient = apigClientFactory.newClient({
     accessKey: 'ACCESS_KEY',
     secretKey: 'SECRET_KEY',
   });
   ```

   To use an API key with the SDK generated by API Gateway, pass the API key as a parameter to the `Factory` object by using code similar to the following. If you use an API key, it is specified as part of the `x-api-key` header and all requests to the API will be signed. This means you must set the appropriate CORS Accept headers for each request.

   ```
   var apigClient = apigClientFactory.newClient({
     apiKey: 'API_KEY'
   });
   ```

   

1. Call the API methods in API Gateway by using code similar to the following. Each call returns a promise with a success and failure callbacks.

   ```
   var params = {
     // This is where any modeled request parameters should be added.
     // The key is the parameter name, as it is defined in the API in API Gateway.
     param0: '',
     param1: ''
   };
   
   var body = {
     // This is where you define the body of the request,
   };
   
   var additionalParams = {
     // If there are any unmodeled query parameters or headers that must be
     //   sent with the request, add them here.
     headers: {
       param0: '',
       param1: ''
     },
     queryParams: {
       param0: '',
       param1: ''
     }
   };
   
   apigClient.methodName(params, body, additionalParams)
       .then(function(result){
         // Add success callback code here.
       }).catch( function(result){
         // Add error callback code here.
       });
   ```

   Here, the *methodName* is constructed from the method request's resource path and the HTTP verb. For the SimpleCalc API, the SDK methods for the API methods of 

   ```
   1. GET /?a=...&b=...&op=...
   2. POST /
   
      { "a": ..., "b": ..., "op": ...}
   3. GET /{a}/{b}/{op}
   ```

   the corresponding SDK methods are as follows:

   ```
   1. rootGet(params);      // where params={"a": ..., "b": ..., "op": ...} is resolved to the query parameters
   2. rootPost(null, body); // where body={"a": ..., "b": ..., "op": ...}
   3. aBOpGet(params);      // where params={"a": ..., "b": ..., "op": ...} is resolved to the path parameters
   ```

   

# Use a Ruby SDK generated by API Gateway for a REST API


The following procedure shows how to use a Ruby SDK generated by API Gateway.

**Note**  
These instructions assume you already completed the instructions in [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md).

**To install, instantiate, and call a Ruby SDK generated by API Gateway for a REST API**

1. Unzip the downloaded Ruby SDK file. The generated SDK source is shown as follows.  
![\[Unzip the downloaded Ruby SDK file into a Ruby module\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/ruby-gem-of-generated-sdk-for-simplecalc.png)

   

1.  Build a Ruby Gem from the generated SDK source, using the following shell commands in a terminal window:

   ```
   # change to /simplecalc-sdk directory
   cd simplecalc-sdk
   
   # build the generated gem
   gem build simplecalc-sdk.gemspec
   ```

   After this, **simplecalc-sdk-1.0.0.gem** becomes available.

1.  Install the gem:

   ```
   gem install simplecalc-sdk-1.0.0.gem
   ```

1.  Create a client application. Instantiate and initialize the Ruby SDK client in the app:

   ```
   require 'simplecalc-sdk'
   client = SimpleCalc::Client.new(
       http_wire_trace: true,
       retry_limit: 5,
       http_read_timeout: 50
   )
   ```

   If the API has authorization of the `AWS_IAM` type is configured, you can include the caller's AWS credentials by supplying `accessKey` and `secretKey` during the initialization:

   ```
   require 'pet-sdk'
   client = Pet::Client.new(
       http_wire_trace: true,
       retry_limit: 5,
       http_read_timeout: 50,
       access_key_id: 'ACCESS_KEY',
       secret_access_key: 'SECRET_KEY'
   )
   ```

1.  Make API calls through the SDK in the app. 
**Tip**  
 If you are not familiar with the SDK method call conventions, you can review the `client.rb` file in the generated SDK `lib` folder. The folder contains documentation of each supported API method call.

   To discover supported operations:

   ```
   # to show supported operations:
   puts client.operation_names
   ```

   This results in the following display, corresponding to the API methods of `GET /?a={.}&b={.}&op={.}`, `GET /{a}/{b}/{op}`, and `POST /`, plus a payload of the `{a:"…", b:"…", op:"…"}` format, respectively:

   ```
   [:get_api_root, :get_ab_op, :post_api_root]
   ```

   To invoke the `GET /?a=1&b=2&op=+` API method, call the following the Ruby SDK method:

   ```
   resp = client.get_api_root({a:"1", b:"2", op:"+"})
   ```

   To invoke the `POST /` API method with a payload of `{a: "1", b: "2", "op": "+"}`, call the following Ruby SDK method:

   ```
   resp = client.post_api_root(input: {a:"1", b:"2", op:"+"})
   ```

   To invoke the `GET /1/2/+` API method, call the following Ruby SDK method:

   ```
   resp = client.get_ab_op({a:"1", b:"2", op:"+"})
   ```

   The successful SDK method calls return the following response:

   ```
   resp : {
       result: {
           input: {
               a: 1,
               b: 2,
               op: "+"
           },
           output: {
               c: 3
           }
       }
   }
   ```

# Use iOS SDK generated by API Gateway for a REST API in Objective-C or Swift


In this tutorial, we will show how to use an iOS SDK generated by API Gateway for a REST API in an Objective-C or Swift app to call the underlying API. We will use the [SimpleCalc API](simple-calc-lambda-api.md) as an example to illustrate the following topics:
+ How to install the required AWS Mobile SDK components into your Xcode project
+ How to create the API client object before calling the API's methods
+ How to call the API methods through the corresponding SDK methods on the API client object
+ How to prepare a method input and parse its result using the corresponding model classes of the SDK

**Topics**
+ [

## Use generated iOS SDK (Objective-C) to call API
](#how-to-use-sdk-ios-objc)
+ [

## Use generated iOS SDK (Swift) to call API
](#how-to-generate-sdk-ios-swift)

## Use generated iOS SDK (Objective-C) to call API
Use generated iOS SDK (Objective-C) to call API

Before beginning the following procedure, you must complete the steps in [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md) for iOS in Objective-C and download the .zip file of the generated SDK.

### Install the AWS mobile SDK and an iOS SDK generated by API Gateway in an Objective-C project


The following procedure describes how to install the SDK.

**To install and use an iOS SDK generated by API Gateway in Objective-C**

1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the [SimpleCalc API](simple-calc-lambda-api.md), you may want to rename the unzipped SDK folder to something like **sdk\$1objc\$1simple\$1calc**. In this SDK folder there is a `README.md` file and a `Podfile` file. The `README.md` file contains the instructions to install and use the SDK. This tutorial provides details about these instructions. The installation leverages [CocoaPods](https://cocoapods.org) to import required API Gateway libraries and other dependent AWS Mobile SDK components. You must update the `Podfile` to import the SDKs into your app's Xcode project. The unarchived SDK folder also contains a `generated-src` folder that contains the source code of the generated SDK of your API.

1. Launch Xcode and create a new iOS Objective-C project. Make a note of the project's target. You will need to set it in the `Podfile`.

      
![\[Find the target in Xcode.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/use-sdk-in-ios-objc-project-find-target.png)

1. To import the AWS Mobile SDK for iOS into the Xcode project by using CocoaPods, do the following:

   1. Install CocoaPods by running the following command in a terminal window:

      ```
      sudo gem install cocoapods
      pod setup
      ```

   1. Copy the `Podfile` file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block:

      ```
      target '<YourXcodeTarget>' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      with your project's target name: 

      ```
      target 'app_objc_simple_calc' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      If your Xcode project already contains a file named `Podfile`, add the following line of code to it:

      ```
      pod 'AWSAPIGateway', '~> 2.4.7'
      ```

   1. Open a terminal window and run the following command:

      ```
      pod install
      ```

      This installs the API Gateway component and other dependent AWS Mobile SDK components.

   1. Close the Xcode project and then open the `.xcworkspace` file to relaunch Xcode.

   1. Add all of the `.h` and `.m` files from the extracted SDK's `generated-src` directory into your Xcode project.

         
![\[.h and .m files are in the generated-src\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/use-sdk-in-ios-objc-project-add-sdk-src.png)

   To import the AWS Mobile SDK for iOS Objective-C into your project by explicitly downloading AWS Mobile SDK or using [Carthage](https://github.com/Carthage/Carthage#installing-carthage), follow the instructions in the *README.md* file. Be sure to use only one of these options to import the AWS Mobile SDK.

### Call API methods using the iOS SDK generated by API Gateway in an Objective-C project


When you generated the SDK with the prefix of `SIMPLE_CALC` for this [SimpleCalc API](simple-calc-lambda-api.md) with two models for input (`Input`) and output (`Result`) of the methods, in the SDK, the resulting API client class becomes `SIMPLE_CALCSimpleCalcClient` and the corresponding data classes are `SIMPLE_CALCInput` and `SIMPLE_CALCResult`, respectively. The API requests and responses are mapped to the SDK methods as follows:
+ The API request of

  ```
  GET /?a=...&b=...&op=...
  ```

  becomes the SDK method of

  ```
  (AWSTask *)rootGet:(NSString *)op a:(NSString *)a b:(NSString *)b
  ```

  The `AWSTask.result` property is of the `SIMPLE_CALCResult` type if the `Result` model was added to the method response. Otherwise, the property is of the `NSDictionary` type.
+ This API request of

  ```
  POST /
      
  {
     "a": "Number",
     "b": "Number",
     "op": "String"
  }
  ```

  becomes the SDK method of

  ```
  (AWSTask *)rootPost:(SIMPLE_CALCInput *)body
  ```
+ The API request of

  ```
  GET /{a}/{b}/{op}
  ```

  becomes the SDK method of

  ```
  (AWSTask *)aBOpGet:(NSString *)a b:(NSString *)b op:(NSString *)op
  ```

The following procedure describes how to call the API methods in Objective-C app source code; for example, as part of the `viewDidLoad` delegate in a `ViewController.m` file.

**To call the API through the iOS SDK generated by API Gateway**

1. Import the API client class header file to make the API client class callable in the app:

   ```
   #import "SIMPLE_CALCSimpleCalc.h"
   ```

   The `#import` statement also imports `SIMPLE_CALCInput.h` and `SIMPLE_CALCResult.h` for the two model classes.

1. Instantiate the API client class:

   ```
   SIMPLE_CALCSimpleCalcClient *apiInstance = [SIMPLE_CALCSimpleCalcClient defaultClient];
   ```

   To use Amazon Cognito with the API, set the `defaultServiceConfiguration` property on the default `AWSServiceManager` object, as shown in the following, before calling the `defaultClient` method to create the API client object (shown in the preceding example):

   ```
   AWSCognitoCredentialsProvider *creds = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:your_cognito_pool_id];
   AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:creds];
   AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
   ```

1. Call the `GET /?a=1&b=2&op=+` method to perform `1+2`:

   ```
   [[apiInstance rootGet: @"+" a:@"1" b:@"2"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
       _textField1.text = [self handleApiResponse:task];
       return nil;
   }];
   ```

   where the helper function `handleApiResponse:task` formats the result as a string to be displayed in a text field (`_textField1`).

   ```
   - (NSString *)handleApiResponse:(AWSTask *)task {
       if (task.error != nil) {
           return [NSString stringWithFormat: @"Error: %@", task.error.description];
       } else if (task.result != nil && [task.result isKindOfClass:[SIMPLE_CALCResult class]]) {
           return [NSString stringWithFormat:@"%@ %@ %@ = %@\n",task.result.input.a, task.result.input.op, task.result.input.b, task.result.output.c];
       }
       return nil;
   }
   ```

   The resulting display is `1 + 2 = 3`.

1. Call the `POST /` with a payload to perform `1-2`:

   ```
   SIMPLE_CALCInput *input = [[SIMPLE_CALCInput alloc] init];
       input.a = [NSNumber numberWithInt:1];
       input.b = [NSNumber numberWithInt:2];
       input.op = @"-";
       [[apiInstance rootPost:input] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
           _textField2.text = [self handleApiResponse:task];
           return nil;
       }];
   ```

   The resulting display is `1 - 2 = -1`.

1. Call the `GET /{a}/{b}/{op}` to perform `1/2`:

   ```
   [[apiInstance aBOpGet:@"1" b:@"2" op:@"div"] continueWithBlock:^id _Nullable(AWSTask * _Nonnull task) {
       _textField3.text = [self handleApiResponse:task];
       return nil;
   }];
   ```

   The resulting display is `1 div 2 = 0.5`. Here, `div` is used in place of `/` because the [simple Lambda function](simple-calc-nodejs-lambda-function.md) in the backend does not handle URL encoded path variables.

## Use generated iOS SDK (Swift) to call API
Use generated iOS SDK (Swift) to call API

Before beginning the following procedure, you must complete the steps in [Generate SDKs for REST APIs in API Gateway](how-to-generate-sdk.md) for iOS in Swift and download the .zip file of the generated SDK.

**Topics**
+ [

### Install AWS mobile SDK and API Gateway-generated SDK in a Swift project
](#use-sdk-ios-swift-install-sdk)
+ [

### Call API methods through the iOS SDK generated by API Gateway in a Swift project
](#use-sdk-ios-swift-call-api)

### Install AWS mobile SDK and API Gateway-generated SDK in a Swift project


The following procedure describes how to install the SDK.

**To install and use an iOS SDK generated by API Gateway in Swift**

1. Extract the contents of the API Gateway-generated .zip file you downloaded earlier. Using the [SimpleCalc API](simple-calc-lambda-api.md), you may want to rename the unzipped SDK folder to something like **sdk\$1swift\$1simple\$1calc**. In this SDK folder there is a `README.md` file and a `Podfile` file. The `README.md` file contains the instructions to install and use the SDK. This tutorial provides details about these instructions. The installation leverages [CocoaPods](https://cocoapods.org) to import required AWS Mobile SDK components. You must update the `Podfile` to import the SDKs into your Swift app's Xcode project. The unarchived SDK folder also contains a `generated-src` folder that contains the source code of the generated SDK of your API.

1. Launch Xcode and create a new iOS Swift project. Make a note of the project's target. You will need to set it in the `Podfile`.

      
![\[Find the target in Xcode.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-find-target.png)

1. To import the required AWS Mobile SDK components into the Xcode project by using CocoaPods, do the following:

   1. If it is not installed, install CocoaPods by running the following command in a terminal window:

      ```
      sudo gem install cocoapods
      pod setup
      ```

   1. Copy the `Podfile` file from the extracted SDK folder into the same directory containing your Xcode project file. Replace the following block:

      ```
      target '<YourXcodeTarget>' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      with your project's target name as shown: 

      ```
      target 'app_swift_simple_calc' do
          pod 'AWSAPIGateway', '~> 2.4.7'
      end
      ```

      If your Xcode project already contains a `Podfile` with the correct target, you can simply add the following line of code to the `do ... end` loop:

      ```
      pod 'AWSAPIGateway', '~> 2.4.7'
      ```

   1. Open a terminal window and run the following command in the app directory:

      ```
      pod install
      ```

      This installs the API Gateway component and any dependent AWS Mobile SDK components into the app's project.

   1. Close the Xcode project and then open the `*.xcworkspace` file to relaunch Xcode.

   1. Add all of the SDK's header files (`.h`) and Swift source code files (`.swift`) from the extracted `generated-src` directory to your Xcode project.

         
![\[.h and .swift files are in the generated-src\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-add-sdk-src.png)

   1. To enable calling the Objective-C libraries of the AWS Mobile SDK from your Swift code project, set the `Bridging_Header.h` file path on the **Objective-C Bridging Header** property under the **Swift Compiler - General** setting of your Xcode project configuration: 

         
![\[Set the Bridging_Header.h file path under the Swift Compiler - General.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-set-bridging-header.png)
**Tip**  
You can type **bridging** in the search box of Xcode to locate the **Objective-C Bridging Header** property.

   1. Build the Xcode project to verify that it is properly configured before proceeding further. If your Xcode uses a more recent version of Swift than the one supported for the AWS Mobile SDK, you will get Swift compiler errors. In this case, set the **Use Legacy Swift Language Version** property to **Yes** under the **Swift Compiler - Version** setting:

         
![\[Set the Legacy Swift Language Version property to Yes.\]](http://docs.aws.amazon.com/apigateway/latest/developerguide/images/use-sdk-in-ios-swift-project-set-legacy-swift-version.png)

   To import the AWS Mobile SDK for iOS in Swift into your project by explicitly downloading the AWS Mobile SDK or using [Carthage](https://github.com/Carthage/Carthage#installing-carthage), follow the instructions in the `README.md` file that comes with the SDK package. Be sure to use only one of these options to import the AWS Mobile SDK.

### Call API methods through the iOS SDK generated by API Gateway in a Swift project


When you generated the SDK with the prefix of `SIMPLE_CALC` for this [SimpleCalc API](simple-calc-lambda-api.md) with two models to describe the input (`Input`) and output (`Result`) of the API's requests and responses, in the SDK, the resulting API client class becomes `SIMPLE_CALCSimpleCalcClient` and the corresponding data classes are `SIMPLE_CALCInput` and `SIMPLE_CALCResult`, respectively. The API requests and responses are mapped to the SDK methods as follows: 
+ The API request of

  ```
  GET /?a=...&b=...&op=...
  ```

  becomes the SDK method of

  ```
  public func rootGet(op: String?, a: String?, b: String?) -> AWSTask
  ```

  The `AWSTask.result` property is of the `SIMPLE_CALCResult` type if the `Result` model was added to the method response. Otherwise, it is of the `NSDictionary` type.
+ This API request of

  ```
  POST /
      
  {
     "a": "Number",
     "b": "Number",
     "op": "String"
  }
  ```

  becomes the SDK method of

  ```
  public func rootPost(body: SIMPLE_CALCInput) -> AWSTask
  ```
+ The API request of

  ```
  GET /{a}/{b}/{op}
  ```

  becomes the SDK method of

  ```
  public func aBOpGet(a: String, b: String, op: String) -> AWSTask
  ```

The following procedure describes how to call the API methods in Swift app source code; for example, as part of the `viewDidLoad()` delegate in a `ViewController.m` file.

**To call the API through the iOS SDK generated by API Gateway**

1. Instantiate the API client class:

   ```
   let client = SIMPLE_CALCSimpleCalcClient.default()
   ```

   To use Amazon Cognito with the API, set a default AWS service configuration (shown following) before getting the `default` method (shown previously):

   ```
   let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityPoolId: "my_pool_id")        
   let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)        
   AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
   ```

1. Call the `GET /?a=1&b=2&op=+` method to perform `1+2`:

   ```
   client.rootGet("+", a: "1", b:"2").continueWithBlock {(task: AWSTask) -> AnyObject? in
       self.showResult(task)
       return nil
   }
   ```

   where the helper function `self.showResult(task)` prints the result or error to the console; for example: 

   ```
   func showResult(task: AWSTask) {
       if let error = task.error {
           print("Error: \(error)")
       } else if let result = task.result {
           if result is SIMPLE_CALCResult {
               let res = result as! SIMPLE_CALCResult
               print(String(format:"%@ %@ %@ = %@", res.input!.a!, res.input!.op!, res.input!.b!, res.output!.c!))
           } else if result is NSDictionary {
               let res = result as! NSDictionary
               print("NSDictionary: \(res)")
           }
       }
   }
   ```

   In a production app, you can display the result or error in a text field. The resulting display is `1 + 2 = 3`.

1. Call the `POST /` with a payload to perform `1-2`:

   ```
   let body = SIMPLE_CALCInput()
   body.a=1
   body.b=2
   body.op="-"
   client.rootPost(body).continueWithBlock {(task: AWSTask) -> AnyObject? in
       self.showResult(task)
       return nil
   }
   ```

   The resultant display is `1 - 2 = -1`.

1. Call the `GET /{a}/{b}/{op}` to perform `1/2`:

   ```
   client.aBOpGet("1", b:"2", op:"div").continueWithBlock {(task: AWSTask) -> AnyObject? in
       self.showResult(task)
       return nil
   }
   ```

   The resulting display is `1 div 2 = 0.5`. Here, `div` is used in place of `/` because the [simple Lambda function](simple-calc-nodejs-lambda-function.md) in the backend does not handle URL encoded path variables.