AWS Mobile
Developer Guide

Add Cloud APIs to Your Mobile App with Amazon API GateWay and AWS Lambda

Cloud Logic Overview

Add RESTful APIs handled by your serverless Lambda functions to extend your mobile app to the range of AWS services and beyond. In Mobile Hub, enabling the Cloud Logic feature uses Amazon API Gateway and AWS Lambda services to provide these capabilities.

Set Up Your Backend

  1. Complete the Get Started steps before your proceed.

  2. Enable Cloud Logic: Open your project in Mobile Hub and choose the Cloud Logic tile to enable the feature.

  3. Create a new API or import one that you created in the API Gateway console.

    1. To create a new API choose Create an API.

    2. Type an API Name and Description.

    3. Configure your Paths. Paths are locations to the serverless AWS Lambda functions that handle requests to your API.

      Choose Create API to deploy a default API and its associated handler function. The default handler is a Node.js function that echoes JSON input that it receives. For more information, see Using AWS Lambda with Amazon API Gateway.

  4. When you are done configuring the feature and the last operation is complete, choose your project name in the upper left to go the project details page. The banner that appears also links there.

  5. Choose Integrate on the app card.

    If you have created apps for more than one platform, the Integrate button of each that is affected by your project changes will flash, indicating that there is an updated configuration file available for each of those versions.

  6. Choose Download Cloud Config and replace the old the version of awsconfiguration.json with the new download. Your app now references the latest version of your backend.

  7. Choose Swift Models to download API models that were generated for your app. These files provide access to the request surface for the API Gateway API you just created. Choose Next and follow the Cloud API documentation below to connect to your backend.

Connect to Your Backend

Use the following steps to add AWS Cloud Logic to your app.

Android - JavaiOS - Swift
Android - Java
  1. Set up AWS Mobile SDK components with the following Set Up Your Backend steps.

    1. Add the following to your app/build.gradle:

      dependencies{ // other dependencies . . . compile 'com.amazonaws:aws-android-sdk-apigateway-core:2.6.+' }
    2. For each Activity where you make calls to API Gateway, declare the following imports. Replace the portion of the first declaration, denoted here as idABCD012345.NAME-OF-YOUR-API-MODEL-CLASS, with class id and name of the API model that you downloaded from your Mobile Hub project.

      You can find these values at the top of the ./src/main/java/com/amazonaws/mobile/api/API-CLASS-ID/ file of the download.

      // This statement imports the model class you download from |AMH|. import; import; import; import com.amazonaws.mobileconnectors.apigateway.ApiClientFactory; import com.amazonaws.mobileconnectors.apigateway.ApiRequest; import com.amazonaws.mobileconnectors.apigateway.ApiResponse; import com.amazonaws.util.IOUtils; import com.amazonaws.util.StringUtils; import;
    3. The location where you downloaded the API model file(s) contains a folder for each Cloud Logic API you created in your Mobile Hub project. The folders are named for the class ID assigned to the API by API Gateway. For each folder:

      1. In a text editor, open ./src/main/java/com/amazonaws/mobile/api/YOUR-API-CLASS-ID/

      2. Copy the package name at the top of the file with the form:{api-class-id}.

      3. In Android Studio, right-choose app/java, and then choose New > Package.

      4. Paste the package name you copied in a previous step and choose OK.

      5. Drag and drop the contents of the API class folder into the newly created package. The contents include and the model folder.

  2. Invoke a Cloud Logic API.

    The following code shows how to invoke a Cloud Logic API using your API's client class, model, and resource paths.

    import; import android.os.Bundle; import android.util.Log; import com.amazonaws.http.HttpMethodName; import; import java.util.HashMap; import com.amazonaws.mobileconnectors.api.YOUR-API-CLASS-ID.YOUR-API-CLASS-NAMEMobilehubClient; import com.amazonaws.mobileconnectors.apigateway.ApiClientFactory; import com.amazonaws.mobileconnectors.apigateway.ApiRequest; import com.amazonaws.mobileconnectors.apigateway.ApiResponse; import com.amazonaws.util.StringUtils; public class MainActivity extends AppCompatActivity { private static final String LOG_TAG = MainActivity.class.getSimpleName(); private YOUR-API-CLASS-NAMEMobileHubClient apiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the client apiClient = new ApiClientFactory() .credentialsProvider(AWSMobileClient.getInstance().getCredentialsProvider()) .build(YOUR-API-CLASS-NAMEMobileHubClient.class); } public callCloudLogic() { // Create components of api request final String method = "GET"; final String path = "/items"; final String body = ""; final byte[] content = body.getBytes(StringUtils.UTF8); final Map parameters = new HashMap<>(); parameters.put("lang", "en_US"); final Map headers = new HashMap<>(); // Use components to create the api request ApiRequest localRequest = new ApiRequest(apiClient.getClass().getSimpleName()) .withPath(path) .withHttpMethod(HttpMethodName.valueOf(method)) .withHeaders(headers) .addHeader("Content-Type", "application/json") .withParameters(parameters); // Only set body if it has content. if (body.length() > 0) { localRequest = localRequest .addHeader("Content-Length", String.valueOf(content.length)) .withBody(content); } final ApiRequest request = localRequest; // Make network call on background thread new Thread(new Runnable() { @Override public void run() { try { Log.d(LOG_TAG, "Invoking API w/ Request : " + request.getHttpMethod() + ":" + request.getPath()); final ApiResponse response = apiClient.execute(request); final InputStream responseContentStream = response.getContent(); if (responseContentStream != null) { final String responseData = IOUtils.toString(responseContentStream); Log.d(LOG_TAG, "Response : " + responseData); } Log.d(LOG_TAG, response.getStatusCode() + " " + response.getStatusText()); } catch (final Exception exception) { Log.e(LOG_TAG, exception.getMessage(), exception); exception.printStackTrace(); } } }).start(); } }
iOS - Swift
  1. Set up AWS Mobile SDK components with the following Set Up Your Backend steps.

    1. Podfile that you configure to install the AWS Mobile SDK must contain:

      platform :ios, '9.0' target :'YOUR-APP-NAME' do use_frameworks! pod 'AWSAuthCore', '~> 2.6.13' pod 'AWSAPIGateway', '~> 2.6.13' # other pods end

      Run pod install --repo-update before you continue.

    2. Classes that call API Gateway APIs must use the following import statements:

      import AWSAuthCore import AWSCore import AWSAPIGateway
    3. Add the backend service configuration and API model files that you downloaded from the Mobile Hub console, The API model files provide an API calling surface for each API Gateway API they model.

      1. From the location where you downloaded the data model file(s), drag and drop the ./AmazonAws/API folder into the Xcode project folder that contains AppDelegate.swift.

        Select Copy items if needed and Create groups, if these options are offered.

        If your Xcode project already contains a Bridging_Header.h file then open ./AmazonAws/Bridging_Header.h, copy the import statement it contains, and paste it into your version of the file.

        If your Xcode project does not contain a Bridging_Header.h file then:

        1. Drag and drop ./AmazonAws/Bridging_Header.h into the Xcode project folder that contains AppDelegate.swift.

        2. Choose your project root in Xcode, then choose Build Settings, and search for "bridging headers"

        3. Choose Objective-C Bridging Header, press your return key, and type the path within your Xcode project:


  2. Invoke a Cloud Logic API.

    To invoke a Cloud Logic API, create code in the following form and substitute your API's client class, model, and resource paths.

    func doInvokeAPI() { // change the method name, or path or the query string parameters here as desired let httpMethodName = "POST" // change to any valid path you configured in the API let URLString = "/items" let queryStringParameters = ["key1":"{value1}"] let headerParameters = [ "Content-Type": "application/json", "Accept": "application/json" ] let httpBody = "{ \n " + "\"key1\":\"value1\", \n " + "\"key2\":\"value2\", \n " + "\"key3\":\"value3\"\n}" // Construct the request object let apiRequest = AWSAPIGatewayRequest(httpMethod: httpMethodName, urlString: URLString, queryParameters: queryStringParameters, headerParameters: headerParameters, httpBody: httpBody) // Create a service configuration object for the region your AWS API was created in let serviceConfiguration = AWSServiceConfiguration( region: AWSRegionType.USEast1, credentialsProvider: AWSMobileClient.sharedInstance().getCredentialsProvider()) YOUR-API-CLASS-NAMEMobileHubClient.register(with: serviceConfiguration!, forKey: "CloudLogicAPIKey") // Fetch the Cloud Logic client to be used for invocation let invocationClient = YOUR-API-CLASS-NAMEMobileHubClient(forKey: "CloudLogicAPIKey") invocationClient.invoke(apiRequest).continueWith { ( task: AWSTask) -> Any? in if let error = task.error { print("Error occurred: \(error)") // Handle error here return nil } // Handle successful result here let result = task.result! let responseString = String(data: result.responseData!, encoding: .utf8) print(responseString) print(result.statusCode) return nil } }