Overview

About this codelab

  • The entire codelab (excluding optional steps) should take about two hours
  • There are time estimates included with each numbered step, so you can pace yourself
  • There are also un-numbered introductory steps that should take 20 minutes or less
  • If you get stuck, checkpoint .zip files are included periodically — just download one and pick up where it leaves off (but make sure to reset any configuration parameters to what you set for your own application)

Why we're here

  • App Engine makes a great backend for mobile applications:
    • Easy to get started
    • Easy to scale
    • Easy to maintain
    • Easy to manage
    • Pay for what you use

Introducing Google Cloud Endpoints

  • Easy to create a scalable API, hosted on App Engine, leveraging Google's API infrastructure
  • Shares many of the same tools and features that make Google's own APIs easy to use:
    • Automatic discovery powering the APIs Explorer and dynamic client libraries (e.g. JS)
    • Statically-typed client libraries in Java and Objective-C
    • Built-in support for OAuth 2
    • Runs at Google scale

Stop talking and show me a demo!

That's cool! Are we going to build that?

In this codelab we're going to:

  • Write two APIs using Google App Engine
  • Extend an Android application using those APIs

But first, some prerequisites

But first, some prerequisites

The following items are helpful, but not required:

  • Experience developing Android applications
  • A physical Android device for testing

Architecture of Tic Tac Toe

Architecture of Tic Tac Toe

Architecture diagram

Let's start building

Step 1: import the starter project

20 minutes

  • Download and unzip this Google App Engine starter project
  • In Eclipse, select File->Import…
  • Expand General, select Existing Projects into Workspace, and click Next >
  • Click Browse… and select the project directory
  • Click the option to Copy projects into workspace
  • Click Finish
  • Right-click the application directory in the Package Explorer and select Run As->Web Application
  • Verify the application is running by visiting http://localhost:8888
  • Return to Eclipse and stop the application

Step 2: configure the starter project

10 minutes

  • In Eclipse, right-click on your application directory in the Package Explorer and select Google->App Engine Settings…
  • Enter the app ID that was whitelisted for the Google Cloud Endpoints feature into the box entitled Application ID
  • Click OK
  • Right-click the application directory again and select Google->Deploy to App Engine
  • Enter your Google account credentials if prompted
  • Confirm your application is running by visiting http://your_app_id.appspot.com

Step 3: add annotations to our Cloud Endpoints

20 minutes

Annotations tell the SDK how our classes should respond to API requests:

  • The @Api annotation indicates the class is an API
  • The @ApiMethod annotation indicates the method is an API method
  • The @Named annotation indicates a method argument is a named parameter in an API request

Check out an example on the next slide…

Step 3: add annotations to our Cloud Endpoints

20 minutes

@Api(name = "tictactoe")
public class ScoreEndpoint {
  @ApiMethod(name = "scores.get")
  public Score get(@Named("id") String id) {
    PersistenceManager pm = getPersistenceManager();
    Score score = pm.getObjectById(Score.class, id);
    pm.close();
    return score;
  }

  // continued on next slide ...
}

Step 3: add annotations to our Cloud Endpoints

20 minutes

@Api(name = "tictactoe")
public class ScoreEndpoint {
  // continued from previous slide ...

  @ApiMethod(name = "scores.list")
  public List<Score> list() {
    PersistenceManager pm = getPersistenceManager();
    Query query = pm.newQuery(Score.class);
    return (List<Score>) pm.newQuery(query).execute();
  }
}

Step 3: add annotations to our Cloud Endpoints

20 minutes

For this step, look for the TODOs in ScoreEndpoint.java:

  • Add the @Api annotation to ScoreEndpoint to it part of the tictactoe API
  • Add the @ApiMethod to the get, list and insert methods of ScoreEndpoint, giving them a "pretty name" (e.g. scores.list)

Step 3: add annotations to our Cloud Endpoints

Solution

Stuck? Download this file which contains the steps we just completed

Step 4: test locally

10 minutes

  • Right-click the application directory in the Package Explorer and select Run As->Web Application
  • Open a new terminal window
  • Run the following command in curl:
    curl --header "Content-Type: application/json" -X POST -d '{"state": "----X----"}' http://localhost:8888/_ah/api/tictactoe/v1/board
  • Confirm that you received a valid JSON response from curl, for example:
    { "state" : "O---X----" }
  • Return to Eclipse and stop the application
  • Deploy your application to App Engine
  • Run the command against your deployed application:
    curl --header "Content-Type: application/json" -X POST -d '{"state": "----X----"}' https://your_app_id.appspot.com/_ah/api/tictactoe/v1/board

Step 5: generate static libraries

5 minutes

  • Right-click on your application directory in the Package Explorer and select Google->Generate Cloud Endpoint Library…
  • In the Finder (or Explorer, file manager of choice, etc.) open the directory containing your application
  • Open endpoint-libs/libtictactoe-v1/tictactoe
  • This is the generated source that allows you to interact with your API — feel free to take a look at the generated code

Step 5: generate static libraries

Solution

Stuck? Download this file which contains the steps we just completed

Step 6: import a starter Android project

20 minutes

  • Download and unzip this Android starter project
  • In Eclipse, select File->Import…
  • Expand General, select Existing Projects into Workspace, and click Next >
  • Click Browse… and select the project directory
  • Click the option to Copy projects into workspace
  • Click Finish
  • If you have Android 2.2 (API 8) installed, the sample will just work. If you do not, right-click the project and select Properties. Select Android. Check the Google APIs option for whichever version of the API (>=8) that you do have installed and click OK.
  • Right-click the application directory in the Package Explorer and select Run As->Android Application. (You'll need to create an AVD in the AVD Manager (Window->AVD Manager) if you aren't testing on a physical Android device.)
  • You should see an application UI, but one that appears to be incomplete

Step 7: integrate your Endpoints with the Android project

30 minutes

Let's use the library we generated in step 5 to integrate our Endpoints into an Android Tic Tac Toe game:

  • We have already included the generated library from step 5 in the Android starter project, however it points to a test App Engine app
  • In Eclipse, edit the com.google.api.services.tictactoe.Tictactoe.java file, changing DEFAULT_CODE_URL to point to your appspot domain
  • Then, edit the TictactoeActivity.java file, completing the sections marked with a TODO with the appropriate calls to the service object (this calls your Endpoints)
  • When you've finished, run your application locally and play a game!
  • Hints are provided on the following slides…

Step 7: integrate your API into an Android Tic Tac Toe game

30 minutes

// Get the computer's next move
Board newBoard = service.board().getmove(boards[0]).execute(); // boards[0] is type Board

// Save the outcome of the game on the server
service.scores().insert(scores[0]).execute(); // scores[0] is type Score

// List the outcome of previous games
ScoreCollection scores = service.scores().list().execute();

Step 7: integrate your API into an Android Tic Tac Toe game

Solution

Stuck? Download this file which contains the steps we just completed

And you're done!

You've finished the codelab! Feel free to work on the optional section for the remainder of the time, or bask in the glory of your awesomeness!

Optional: try the API with JavaScript

  • Copy the HTML from this boilerplate page into the index.html file of your App Engine project
  • Search for ROOT in the code and change your_app_id.appspot.com to the correct value for your app
  • Save the file
  • Run the App Engine application locally
  • Visit your deployed app and open the JavaScript Console (View->Developer->JavaScript Console)
  • Experiment with the JS client by running the commands on the following page in the JavaScript Console…

Optional: try the API with JavaScript

// Insert a score
gapi.client.tictactoe.scores.insert({'outcome': 'WON'}).execute(function(resp) {
  console.log(resp);
});

// Get the list of previous scores
gapi.client.tictactoe.scores.list().execute(function(resp) {
  console.log(resp);
});

Optional: integrate with a web game

  • Copy the HTML from this partially completed page into the index.html file of your App Engine project
  • Search for ROOT in the code and change your_app_id.appspot.com to the correct value for your app
  • Look for all the sections marked with a TODO and fill them in using the appropriate calls to your Endpoints
  • When you've finished, run your application locally and play a game!

Optional: integrate with a web game

Stuck? This file contains the completed HTML and JS

Thank You!