Google Cloud Endpoints Tutorial – Part 7

Welcome to Part 7 of the Google Cloud Endpoints Tutorial.

The full series:

  • Part 1 : We looked at writing a Google Cloud Endpoints class manually by using the various annotations and Exception classes that are available. We create a Quotes API that provided a JSON + REST based interface to manage Quotes (add, modify, delete and retrieve quotes).
  • Part 2 : We generated the Google Cloud Endpoints class from a JDO Annotated Entity class by using the Code Generation tools provided in the library.
  • Part 3 : Generated the Cloud Endpoints Client Library for Android and wrote an Android application that invokes the Endpoints API.
  • Part 4: We wrote a JavaScript client for our Endpoints API.
  • Part 5: Securing our API
  • Part 6: Calling a Secured API from a JavaScript client.
  • Part 7 : Calling a Secured API from an Android client.

I have also published a list of Cloud Endpoints Tips:

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotations
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation

In this episode

So far in this series, we looked at writing a Quote API and in the last couple of episodes, we introduced how to secure your API methods so that only authorized clients can invoke the methods and we demonstrated how to make secure calls from our JavaScript client.

In this episode, we shall see how to make secure API calls from our Android client.

What do you need ?

  • You have a working development environment for Google App Engine. This includes the Google Eclipse plugin.
  • The API Project 2 (Quotes Endpoint Project) loaded in your Development Environment. This is the same as the previous episode.
  • You have a working development environment for Android. I have used Eclipse with the ADT Plug-in.
  • Basic understanding of Android Application Development. We will be using the same code that we had used in Part 3 : Writing an Android client.

My Development Environment

  • This remains the same, no changes at all. My development environment is given below:
    • Eclipse Juno
    • Google Eclipse plugin with App Engine SDK 1.8.8
    • Android ADT Plugin with latest Android SDK installed.
    • Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Invoking the Secure API from Android client

In the last post, we had demonstrated how to make a secured call to the insertQuote method from a JavaScript client. In the Android version of that in this episode, we will be using the same code as we have used in Part 3, except that in the Add Quote Activity, we shall be modifying our code to make secured calls from the Android native application.

Let us first revisit the whole thing about Web Client Id and Audiences that we had setup for our Quotes API earlier.

Web Client Id

If you recollect, in the earlier episode, we had visit the Google Cloud Console for our project and create the OAuth Client Id. A screenshot of the Web Client Id is shown below.

Screen Shot 2014-02-14 at 8.45.01 PM

We created a Constants.java file that contained all these IDs as given below:

Notice that the ANDROID_AUDIENCE is what we are going to use here and it has been set to the same value as the WEB_CLIENT_ID.

Additionally, we had updated the @APIMethod for insertQuote and provided the clientIds, that included the Web Client Id and then deployed the API.

Again notice that we have specified the Client Ids that can access the insertQuote method and also mentioned the ANDROID_AUDIENCE in the audiences attribute.

Remember to regenerate your Client Libraries, just in case you have not done so and deploy it as needed. 

Famous Quotes Android Application Code

We are going to use the same code base as the original Famous Quotes Android application that was covered in Part 3I strongly suggest to go through that first to ensure that you have your Android application and all dependencies set up correctly.

If you want to download that source code, it is available here.

Play Services SDK

Since we are going to make an authenticated call from the Android client, the process will be that we will use the currently logged in Google Account on your Android device. Since this requires Account Picker and other classes on Android from the Play Services Library, it is required that you download the correct Play Services SDK and set that up as a library in the application.

Make sure you link up to the correct library depending on the version that you want to target. I tried out my code on a Android 2.3 device too and it bombed with the latest version of the Play Services SDK. As a result of which, I had to link up to a Froyo version of the library.

So, the first thing to do is to ensure that you have the Play Services SDK. For e.g. in the Android SDK Manager, you can see it over here:

cep7-1

Once you install (download) the above packages, they will be available in the ADT Folder\sdk\extras\google folder as given below:

cep7-2

Simply go to your Eclipse environment and Import any of the above projects as applicable. These are Android library projects and make sure you are able to import it successfully. 

Next, simply add the Play Services library project to your Famous Quotes Android application. The Properties page with the library linked up successfully is shown below:

cep7-3

This completes the development environment setup.

Let us look at the parts of the Add Quote Activity that we modified to ensure that the correct credentials are passed over behind the scenes while making the secure calls from the Android client.

AddQuote Activity Source Code

The entire source code for the AddQuote Activity is shown below:

Let us focus on the important parts and how the Account Credentials are setup before invoking the Secure Cloud Endpoints API.

  • Pay attention first to the onCreate(…) method. The code is identical to the earlier one where we setup the onclick listener for the AddQuote button.
  • There is a section starting with the comment //Account Stuff and there we create an instance of the GoogleAccountCredential class. We create that using the usingAudience method. Notice that the Audience Id string has to be created as follows “server:client_id:<AudienceId>
  • Once the GoogleAccountCredential instance is setup, we invoke the setAccountName method. This method uses Android SharedPreferences , to determine if an ACCOUNT_NAME String preference value was set. If yes, we set that account name for the GoogleAccountCredential instance.
  • We check in the next line if the name has been selected, if not – we invoke the chooseAccount() method, that starts the standard Account Picker activity on your Android phone. This will allow you either login or choose from one or more of your accounts on the device. Once selected, we invoke the setAccountName() method again to set the account name in the GoogleAccountCredential instance and set the value in the SharedPreferences too.
  • Now that the the GoogleAccountCredential is all set, the other change you will notice is in the AddQuoteAsyncTask.
  • In the doInBackground method, notice the following line:
    Quoteendpoint.Builder builder = new Quoteendpoint.Builder(
                    AndroidHttp.newCompatibleTransport(),
                    new GsonFactory(),
                    credential);

    Here, we are no longer passing null in the 3rd parameter. We are using the GoogleAccountCredential instance.

AndroidManifest.xml Permissions

We need to add some additional permissions to the AndroidManifest.xml file as given below:

Project Source Code – Download

The source code for the MyAPIProject2 is available in Github. You can download the entire source code over here.

Additionally, the source code for the secure FamousQuotes Android application is also provided over here.

This brings to an end, the series on Cloud Endpoints as I had originally planned out. Hope you liked the series so far. Give me feedback to help me create more and better content.

I do hope to blog about comparing Google Cloud Endpoints with other methods of writing Web Services along with some stuff that I would ideally like the next release of Google Cloud Endpoints to address both in features, samples and documentation.

About these ads

About rominirani

Google Developer Expert Cloud 2014. Harnessing the power of software by learning, teaching and developing simple solutions. I love learning about new technologies and teaching it to others.
This entry was posted in Cloud Computing, Google App Engine. Bookmark the permalink.

12 Responses to Google Cloud Endpoints Tutorial – Part 7

  1. Pingback: Google Cloud Endpoints Tutorial – Part 1 | iRomin

  2. Pingback: Google Cloud Endpoints Tutorial – Part 6 | iRomin

  3. Very nice series, thank you. As far as more content goes, I am wondering about Cloud Endpoints and Service Accounts. From what I have read, it seems this is not currently supported.

    • rominirani says:

      Thats a very good suggestion. Is your use case, the ability to call secured endpoints from another app engine application , without the need to authenticate ?

  4. Sid says:

    Thanks for this tutorial.

    Q1 – Is there anyway to hide my API definitions from the public? I have uploaded my app to appengine however looks like anyone on the internet can access .appspot.com/_ah/api/explorer and view and input data.

    Q2 – I’m building an Android client which does not require authentication from the user for some APIs. Basically the user does not need to login to view some screens.
    However I only want my Android app to access those APIs? How can I go about doing this. Do you recommend any other solution other than http://stackoverflow.com/questions/21825175/how-do-i-restrict-google-app-engine-endpoints-api-access-to-only-my-android-appl

    • rominirani says:

      1. I am not sure if that can be done via a simple configuration setting or something like that. I am not aware of that.
      2. I believe you can do that by trying to specify the Client Ids, Audiences, etc in the @APIMethod. The user object would be null. But still give that a try and see if it works.

  5. Pingback: Google Cloud Endpoints Tutorial – Part 5 | iRomin

  6. Pingback: Google Cloud Endpoints Tutorial – Part 4 | iRomin

  7. Pingback: Google Cloud Endpoints Tutorial – Part 3 | iRomin

  8. Pingback: Google Cloud Endpoints Tutorial – Part 2 | iRomin

  9. Gregory says:

    Thanks for this tutorial.
    but i have a problem, if you can help please.
    in line response = service.insertQuote(quote).execute();
    i have exception: com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAuthIOException

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s