Build a Mobile App Using Google Compute Engine and REST

Running your mobile backend on Google Compute Engine and using REST as the communication protocol between your mobile app and the backend server has several advantages.

  • It is the fastest way to move an existing service, running on an on-premises or virtual machine, to Google Cloud Platform.
  • It gives you full control over your virtual machine and server configuration.
  • You can use third party libraries.
  • You can configure an autoscaler to scale the number of virtual machines to meet demand.

The downside to running your service on Compute Engine is that you are responsible for maintaining and updating your server manually. For other options for building mobile backend services, see Build mobile apps using Google Cloud Platform.

This tutorial walks you through building a sample mobile app called Stickynotes. This sample app uses REST to connect to a backend service running on Compute Engine.

The Stickynotes sample includes code for a frontend mobile app and a backend service. In the mobile app, you can enter a message into a text field. The app sends your message to a backend service using REST. The backend service which converts the text message into an image using draw2d, and then returns the image to the mobile app. The mobile app then displays your message as an image with a yellow background.

The client app is an iOS app and the backend service is written in Go.

Objectives

In this tutorial you will learn how to:

  • Create an iOS mobile app that uses REST to connect to a backend service.
  • Configure and run a REST backend service on Compute Engine.

Costs

This tutorial uses billable components of Cloud Platform, including:

  • Google Compute Engine

Use the Pricing Calculator to generate a costc estimate based on your projected usage. New Cloud Platform users might be eligible for a free trial.

Before you begin

  • Sign in to your Google account.

    If you don't already have one, sign up for a new account.

  • Select or create a Cloud Platform project.

    Go to the Manage resources page

  • Enable billing for your project.

    Enable billing

  • Install the following software:

    Clone the sample code

    git clone https://github.com/GoogleCloudPlatform/ios-docs-samples.git
    

    Then navigate to /solutions/stickynoteapi/REST to find the sample code for this solution.

    Run the server locally

    In the /stickynoteapi/REST/Go directory, run the following command

    sh SETUP
    

    You should see the following output:

    1. Set gopath and search path
    2. Get the server and client dependencies
    3. Build the server and client
    4. Stop any previously-running instances of the server
    5. Start the server
    6. Run the client
    2016/03/02 11:34:48 OK: message.png
    7. Open the image in message.png
    

    The setup also runs a local client to test the server with the phrase “Remember the milk.” and generates an image with that message.

    Remember the milk.

    To generate images based on your own messages using the command-line client, run the following command.

    ./client "This is a test..."
    

    The file, /stickynoteapi/REST/Go/go/src/server/server.go, contains the code that runs the REST server. The main function defines a handler for the root-level directory, and listens for traffic on port 8080. Because the server does not specify an IP address or domain, you can run this code on Compute Engine without any modification.

    func main() {
    	http.HandleFunc("/stickynote", handler)
    	http.ListenAndServe(":8080", nil)
    	//http.ListenAndServeTLS(":443", "ssl.crt", "ssl.key", nil)
    }

    The handler function recieves the message in the REST request, uses functions defined in sticky.go to build an image based on that message, and then returns the image in an REST response.

    func handler(w http.ResponseWriter, r *http.Request) {
    	var sticky Sticky
    	sticky.Message = r.FormValue("message")
    	sticky.Centered = false
    	stickyBytes, err := sticky.DrawPNG(512, 512)
    	if err == nil {
    		w.Write(*stickyBytes)
    	}
    }

    Leave the local server running so you can use it to test the client application.

    Run the iOS client with the local server

    1. In the stickynoteapi/REST/Objective-C/ directory, open stickynotes.xcodeproj in Xcode.
    2. Select Product > Run to build and start the client application.
    3. Enter a message in the text field and tap Return.

    An image of a yellow sticky note with your message should appear beneath the text field.

    This is a test...

    The client app sets the location of the backend service in the file StickyNotesViewController.m. For testing purposes, this is initially set to localhost, on port 8080.

    static NSString * const kHostAddress = @"localhost:8080";

    When you tap Return after entering your message in the text field, the following action fires which encodes the message into a query string and then sends that to the server during an REST session. It displays the generated image an image view.

    - (IBAction) textFieldDidEndEditing:(UITextField *)textField
    {
      NSString *queryString = [NSString stringWithFormat:@"http://%@/stickynote?message=%@",
                               kHostAddress,
                               [textField.text urlencode]];
      NSURL *URL = [NSURL URLWithString:queryString];
      _request = [NSMutableURLRequest requestWithURL:URL];
    
      NSURLSession *session = [NSURLSession sharedSession];
      _task = [session dataTaskWithRequest:_request
                         completionHandler:
               ^(NSData *data, NSURLResponse *response, NSError *error) {
                 UIImage *image = [UIImage imageWithData:data];
                 dispatch_async(dispatch_get_main_queue(), ^{
                                  self.imageView.image = image;
                                });
               }];
      [_task resume];
    }

    Run the server on Google Compute Engine

    1. Go to the Create an instance page in the Google Cloud Platform Console.
      Go to the Create an instance page

      1. Set Name to sticky-rest.
      2. Check the Allow HTTP traffic and Allow HTTPS traffic checkboxes.
      3. Select Create.

      Create an instance

    2. Go to the View your VM instances page in the Cloud Platform Console.
      Go to the View your VM instances page

      1. Note the External IP address next to sticky-rest.
      2. Select SSH

      Select SSH

    3. Install Git on the instance.

      sudo apt-get update
      sudo apt-get install git
      
    4. Install Go.

      sudo wget https://storage.googleapis.com/golang/go1.6.linux-amd64.tar.gz
      sudo tar -C /usr/local -xzf go1.6.linux-amd64.tar.gz
      export PATH="/usr/local/go/bin:${PATH}"
      
    5. Clone the Stickynotes server code.

      git clone https://github.com/GoogleCloudPlatform/ios-docs-samples.git
      
    6. Start the Stickynotes server on the instance. In the /solutionsgp/stickynoteapi/REST/Go directory, run the following command.

      sh SETUP
      
    7. In Xcode, edit StickyNotesViewController.m to change localhost to the external IP address of your Compute Engine instance from Step 2.

      // static NSString \* const kHostAddress = @"localhost:8080";
      static NSString \* const kHostAddress = @"198.51.100.0:8080";
      
    8. Select File > Save to save your changes.

    9. Select Product > Run to build and start the client application.

    10. Enter a message in the text field and tap Return.

    An image of a yellow sticky note with your message should replace the gray background.

    Testing on remote server...

    Cleaning up

    To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

    Deleting the project

    The easiest way to eliminate billing is to delete the project you created for the tutorial.

    To delete the project:

    1. In the Cloud Platform Console, go to the Projects page.

      Go to the Projects page

    2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    Deleting instances

    To delete a Compute Engine instance:

    1. In the Cloud Platform Console, go to the VM Instances page.

      Go to the VM Instances page

    2. Click the checkbox next to the instance you want to delete.
    3. Click the Delete button at the top of the page to delete the instance.

    Deleting firewall rules for the default network

    To delete a firewall rule:

    1. In the Cloud Platform Console, go to the Firewall Rules page.

      Go to the Firewall Rules page

    2. Click the checkbox next to the firewall rule you want to delete.
    3. Click the Delete button at the top of the page to delete the firewall rule.

    What's next

    This sample demonstrates the basics of how to connect a mobile app to code running on Compute Engine using REST. To extend this sample into a real app, consider adding the following enhancements:

    • Add a static IP address to your server -- by default, the external address associated with a Compute Engine instance is transient. For a production app you should attach a static IP address to your instance. For more information, see Configuring an Instance’s IP Address.

    • Use credentials to connect to an HTTPS server -- ensure that your backend service can only be called by your mobile app by requiring your mobile app to use credentials to authenticate itself to the server. Protect the privacy of the data that your users send to the server, by using the encrypted HTTPS protocol instead of HTTP. To do this you could run a NGINX server as an SSL proxy on your instance or run your backend server in the Google App Engine flexible environment. For more information, see Securely Connecting to VM Instances.

    • Add load balancing and autoscaling -- handle traffic spikes gracefully by setting up a load balancer and autoscaler to spin up extra instances when demand grows, and to route traffic evenly across those instances. For more information, see Setting up HTTP(s) Load Balancing and Autoscaling Groups of Instances.

    • Explore using the gRPC protocol instead of REST -- gRPC is a framework that makes it possible for a mobile app to directly call methods on a backend service as if it was a local object. You can use gRPC to make your mobile app more bandwidth-efficient and to reduce latency between your app and backend service running on Cloud Platform. For an example of how to use gRPC in the Stickynotes sample, see Build a mobile app using Google Compute Engine and gRPC

    • Consider other hosting options for your backend service -- Compute Engine offers the greatest degree of control over your virtual machine, but at the cost of you manually updating and managing your instance. For a discussion of other ways to host a mobile backend service on Cloud Platform, see Build mobile apps using Google Cloud Platform.

    Send feedback about...