Google Cloud Endpoints Tips #2 : Throw the Right Exception Classes

One of the hallmarks of a well-written API is to understand what it throws back to the clients when there is an exception.

For e.g. a REST API should make use of the correct HTTP Status Codes in its response. Some of the well-known status codes are 200 (OK) , 404 (Not Found), 500 (Internal Server Error) and so on. It is very important that you implement your Endpoint classes to throw back the correct status codes.

Cloud Endpoints does provide a mechanism for you to throw back Exception classes that will in return use the correct HTTP Status code in the response sent back to the client. As per the documentation, there are several exception classes made available in the com.google.api.server.spi.response package. Some of these exception classes are:

  • NotFoundException (HTTP 404)
  • UnauthorizedException (HTTP 401)

and so on. The usage is simple too. Here is a snippet for throwing a not found exception:

String message ="No entity exists with ID: "+ entityId;throw new NotFoundException(message);

The above would be the correct way to throw an exception. It is easy to make the mistake of throwing some other Java Exception (Persistence Layer), etc. This will result in a crazy response for the client with a trace, etc. So always catch the exceptions being thrown from the layers that Cloud Endpoints interacts with and then instantiate the correct exception.

Note that you can also create your own custom Exception classes that map to some other HTTP Codes. But do look out in the documentation for the status codes that you should not be overriding with your custom exception classes.

 

One of the areas where you will immediately notice the need for the correct exception classes is the default code that is generated for the endpoints from your Entity class. Look at the get and insert methods that it generates and you will find that it throws Entity Exceptions from the Persistence Layer. This is typically not a good idea and it is best to envelope this with the Exception classes that correctly map to the HTTP Codes.

Developers who are writing Client applications against your API and API tools will thank you.

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 Annotation
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation

Google Cloud Platform Roadshow India – Talks & Experience

March 25, 2014 is a day to remember. A day where Google broke through the ranks with a series of announcements that clearly demonstrated that there was no need to play catch up in the Cloud Platform wars. Instead, how about leapfrogging the competition on multiple fronts?  It did exactly that. Check out the Cloud Platform Live Event.

Google India announced the Cloud Platform Roadshow across 5 Indian metros through April – May 2014. The series kicked off in Hyderabad on April 12 and since then has moved across to Chennai, Bengaluru, Mumbai and is set for Delhi this week.

The day-long event had talks on:

  • Recent Cloud Platform announcements from the March 25 event
  • Pricing Details on the Platform
  • Compute Engine : Overview and Live Demo
  • App Engine : Cloud Endpoints – writing APIs at Google Scale
  • Bridging the gap between PaaS and IaaS : Flexibility + Manageability
  • BigQuery : Query TBs of data in seconds ! Yes you can !
  • Case Studies of actual customer implementations
  • Partner product demos

While I did present at these events, my personal favorites were the Compute Engine and BigQuery sessions, where I learnt a lot. I could not help but hear the wow’s of the audience when they saw what BigQuery can do. Janakiram clearly rocked the audience with his Compute Engine sessions. Googler’s Rohit and Anudeep are all set to make their future talks “must attend” with their ‘jugalbandi’ (fusion or beautiful mix) in presenting technical topics.

If its been a while you have taken a look at the Google Cloud Platform, you owe it to yourself to learn about the various services that are now under a single Cloud Platform umbrella and present a more unified and complete solution.

I was delighted to present the App Engine session during these roadshows and I focused on Google Cloud Endpoints, which provides a service to create RESTful APIs powered by the App Engine platform. If you are looking to scale up your APIs and power it with Google’s infrastructure, Endpoints is the way to go. You can check out my slides.

DSC_2103

The number of queries and feedback from the participants was excellent. Some of the questions are solid enough for me to go back and think more on how it can be addressed. It was very encouraging to learn from some of them that they were excited enough to try things out soon and learn more about the platform.

As of writing, the roadshow makes its last stop at Delhi on May 31. If you live in and around Delhi and want to learn about the Google Cloud Platform, come and spend May 31st to get vowed with multiple product demonstrations. Click that Registration link.

Google Cloud Endpoints Tips #1: Check Endpoint Deployment Status

While deploying Cloud Endpoints to a live appspot.com domain, it is important to know if your endpoints deployed OK or not. The Logs Viewer of App Engine provides a good way for you to determine that.

Do the following:

  1. Deploy your App Engine project containing Cloud Endpoints.
  2. Once deployed successfully, go to the App Engine Administration Console and go to Logs Viewer.
  3. Scroll through the recent logs by time-stamp and you shall see something that looks like this:

Image

 

I have 5 Endpoints in my project and for each of the endpoints, it will provide a OK message as shown above.

The above quick tip is referenced from the documentation and it also mentions that in case there was a problem deploying the Endpoint, you should see an ERROR instead of OK.

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

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.

Google Cloud Endpoints Tutorial – Part 6

Welcome to Part 6 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 episode, we introduced how to secure your API methods so that only authorized clients can invoke the methods. We secured the insertQuote method in the last episode and in this episode, we are going to see how to make secure calls from our JavaScript client.

Keep in mind that we had written a JavaScript client for our Endpoints API earlier in Episode 4, so please take a look at that first.

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, except that we will be focusing on the apitest.html , which is our API 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.
  • Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Web Client in Action

Let us first try to understand what we are going to create here by seeing the application and security in action.

I am accessing the client at http://mybackendapi.appspot.com/apitest.html. I have currently logged out from all of my Google Accounts.

When I access the above page, I get the following page:

Screen Shot 2014-02-15 at 2.45.24 PM

Notice the Login button shown above. This button is shown if there was no Google Account that was already logged in. If the User was logged in, this button would be invisible and instead we would be having a Welcome message.

Now, we will not yet click on the Login button. Instead we will attempt to insert a new Quote without logging in and verify if the insertQuote method is indeed secured or not. We enter test values in the Author Name and Quote as shown below and click on the Insert Quote button. This will bring up a popup as shown below. In fact this is the response that we have simply displayed and which came from the Endpoints API HTTP Response:

Screen Shot 2014-02-15 at 2.45.46 PM

In the JavaScript code, I log out the response to the console and which you can see below:

Screen Shot 2014-02-15 at 2.45.57 PM

Now, I click on Login and go through the standard OAuth dance, where I choose a Google Account to log in with, give my credentials and then authorize the application. If all is well, I am logged into our client now and we retrieve the User Name from the OAuth API and display a welcome sign on the top, as shown below:

Screen Shot 2014-02-15 at 2.43.57 PM

Now, I can give my sample values for the Author Name and Quote and click on Insert Quote. 

Screen Shot 2014-02-15 at 2.44.37 PM

The record will get inserted and when I do a List Quotes , I will see the new record that I added:Screen Shot 2014-02-15 at 2.44.57 PM

Let us discuss the code now.

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

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

JavaScript Client

The entire source code for apitest.html is shown below. The code snippets for Login functionality has been borrowed from the sample code provided in the official document by Google.

Let us look at the main points. Parts of the code should be familiar if you have worked with the JavaScript client that was introduced in Part 4 of this series.

  • We have added a Login button to the User Interface.
    <div id=”login”>
    <input id=”loginButton” type=”button” value=”Login”/>
    </div>
  • As covered in an earlier episode, we load the Client API and once the API is loaded, our init method is invoked.
  • In our init method, we are loading two APIs now : the Quote Endpoint API as we have done earlier and the OAuth API.
  • Once both the APIs are successfully loaded, we are invoking the signin method. To the signin method, we are providing two parameters : an immediate mode parameter whose value is set to true and a callback function : handleAuth.
  • In the signin method, we invoke the gapi.auth.authorize method. To that method, we pass the client Id, scope, immediate mode and the callback (handleAuth). Notice that we have initialized the client Id and scope values in the code and they are the same values as the ones we have created via the Google Cloud Console OAuth New Client creation page. These must match for the authentication/authorization to succeed.
  • In the handleAuth method, we get the current User Object. If the User is found with no errors, then we hide the Login button and display the Welcome message. If the User is not found, the Login button is made visible. This is what happens when our page is loaded i.e. Login button is shown or not shown depending on whether the user is logged in or not. This is also known as the immediate mode.
  • Now, if the Login button is shown i.e. authorization still has to be done, then we have a handler for our Login Button as shown below:
    document.getElementById(‘loginButton’).onclick = function() {
             signin(false,handleAuth);
     }
  • If Login Button is clicked, the signin method is called again with the immediate mode set to false and the callback method as the same one i.e. handleAuth. This will invoke the entire Google Login popup and you go through with the Authentication and Authorization cycle.
  • The insertQuote method is slightly modified to display the error in case there is a problem executing the gapi.client.quoteendpoint.insertQuote method.

Project Source Code

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

Hope you liked this episode of the Google Cloud Endpoints tutorial. The next episode will cover making secured API calls from an Android client.

Google Cloud Endpoints Tutorial – Part 5

Welcome to Part 5 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

Security is a key consideration for any application that you host on the public internet. This is especially important when you are writing an API for others to use in their client applications. You need to ensure that the API that you have written is secure, allows only authenticated users to perform operations and so on.

In this episode, we shall look at securing the Quotes API that we have written so far. This episode only focuses on securing the API implementation. Once, we are done with that, in the following episodes that will be published quickly, we shall see how to make authenticated calls from both a JavaScript client and an Android application.

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 project has now been updated to secure certain operations, which we shall cover in this episode. So, if you have an older version of it, you might want to sync with the latest code. Even if you do not want to load it, just follow along in the tutorial to see how to secure your API.

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.
  • Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Securing the Quotes API

Let us recap quickly on what we have done so far. We have written a Quotes API hosted on Google App Engine that allows us to perform CRUD operations via a HTTP REST API. A Quote record contains a couple of attributes, the author and the famous quote that the author gave.

If you look at the API Methods, we had the following methods exposed:

Screen Shot 2014-01-12 at 4.21.42 PM

To secure the API, we need to first determine if we are interested in securing all the methods that we expose or only certain methods. This flexibility is provided to you by Google Cloud Endpoints.

So, what we are going to see in this operation is enabling security for one of the methods: insertQuote. What this means is that if you are not an authorized user, that any call to the insertQuote method will fail. Once you understand how to do it for one method, it should be straight forward for you to extend it to other methods.

Sounds good? Lets move on.

Adding Authorization

Google has clearly documented the steps that we need to follow to add authorization to our API and we will follow that as specified.

Step 1 : Specify the Client Ids

The first thing we need to decide is what kind of clients are we expecting for our API. The usual suspects are a Web client, Android client, iOS client and so on. What this means is that we need to create these client Ids and both the Server side i.e. our API Implementation and the Client need to be aware of these Client Ids, so that the Client can be identified with the Server.

To do that, I will assume that since you have been reading these tutorial series, you have also created an App Engine project. If not, this is the time to do it and there is no other way out from this :-)

To create the client Ids, you will need to visit the Google Cloud Console for your App Engine project. In case, you are yet to deploy your API to the App Engine instance, I suggest this is a good time to create the application.

In my case, I already deployed this API to an App Engine instance (mybackendapi). So I directly visit the Google Cloud Console for my account and from my list of projects, I select the particular API project (in my case again, it is the mybackendapi project)

You will see a similar screen as shown below:

Screen Shot 2014-02-14 at 8.34.27 PM

Go ahead and click on APIs & auth link from the left menu and then the Credentials link as shown below:

Screen Shot 2014-02-14 at 8.37.08 PM

We need to generate a Web Client here and in the later episode, I shall demonstrate how to generate an Android client. But for now, let us just generate the Web Client ID. 

Click on the Create New Client Id button that you see in RED. This lets you create Client Ids for Web, Android and more. You will see a screen as shown below:

cep-ep5-1

The Application Type should be fairly straightforward i.e. it is a Web Application client that we shall write in the next episode. The next field is very important. It allows you to specify an origin from where the JavaScript call will be made and which will need to be authenticated by the Google Authentication Layer. In our case, when the credentials are being provided, the call will be made from either our localhost application where we will run to do some testing or finally when we deploy it, it will be our App Engine application.

You can specify multiple origins here (one on each line). So I have specified the localhost and also the my appengine application origin. The redirect URI is not applicable here and is automatically populated for you. Let that be as is.

Click on the Create Client ID button. This will generate the Client Id and you will see that in your console as shown below:

Screen Shot 2014-02-14 at 8.45.01 PM

Note down the Client ID. You will need it in the next episode when we make make authorized calls from our JavaScript client.

The next step is important and is something that you might forget. It happened to me, at least the first time. 

Click on the Consent screen link. This is the screen that is shown when you are authorizing the application on your behalf. You can fill in all the details but at a minimum, you must fill our the Email address and Product name.

cep-ep5-2

Click on Save button to save your settings for the Consent Screen.

Now that we have created the Client Ids, we need to ultimately provide this information to our Server API i.e. Endpoints API. To help keep all the IDs in one place, Google documentation shows the use of a Constants.java file and that is a good approach to go with. So we will create a Constants.java file and place our Client Ids in that as shown below:

Note the following:

  • We have defined the constant WEB_CLIENT_ID that should contain the value of the Client ID that we just created.
  • The next thing to note is the EMAIL_SCOPE. This is the OAuth 2.0 Scope. 
  • The ANDROID_CLIENT_ID, we have not yet generated. But once we generate it (as we will see in a later episode, you will need to put it here).
  • There is also the ANDROID_AUDIENCE that is given the same value as the WEB_CLIENT_ID. We shall use this in later episode when we create our Android client.

Step 2 : Add the Client Ids, Scope and Audiences to your @API or @APIMethod

We need to first make a decision whether we want to protect all the methods or only some methods. If you want to protect all the methods, you need to deal with the @API annotation or if you are interested in protecting specific methods, then you need to worry about the @APIMethod (i.e. the methods in your class).

As described earlier, we are going to protect only the insertQuote method, so we shall we enhancing the @APIMethod annotation for the insertQuote method as shown below:

Let us take a look at the important points here:

  • We have added 3 attributes to the @APIMethod for the insertQuote method. They are scopes, clientIds and audiences as covered earlier.
  • Note that the clientIds also contains an additional one : com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID and this is required because we are going to use the API Explorer for testing out our API. Makes sense doesn’t it ?

Step 3 : Add the Add a User parameter to your methods

Keep your focus on the above Gist for the insertQuote method. For every method that you want to authorize for, you need to add a User parameter at the end as we have done. If the user is authorized correctly, an instance of the com.google.appengine.api.users.User  class will be passed in here.

But you will need to be careful here. You cannot assume that the object will be populated always. If the Authorization fails, the User object will be null. So you need to do your own little check here as we have.

We check for null value and it that is indeed the case, we throw a com.google.api.server.spi.response.UnauthorizedException, which will be translated by the Endpoints layer into a correct HTTP 401 Status Code. The rest of the code is the standard code from the previous episodes.

That is all  you need to do to the methods. In case you wish to apply this to other methods, you can do that.

Step 4 : Regenerate your APIs

This step is not really needed at this point till we revisit our client applications but safe to say that it is important that you generate the Client Libraries again because you have modified the details for the APIs. To generate your Client Libraries again, it should be familiar to you but I will say it again.

eclipse2

Testing your secured API via the API Explorer

All right ! We have done the hard work of securing the API ? Or have we … let’s find that out!

We will use our good friend, the API Explorer to help us out again. You could do this testing either in your local dev server environment or the live App Engine instance. Just keep in mind that the API explorer is available via the /_ah/api/explorer URL. Remember that we had provided the JavaScript Origins for both our localhost and the app engine instance when defined the Client ID and that is going to hold us good whether we test in our local environment or the live environment.

In my case, I am testing the same in my local dev environment. I visit http://localhost:8888/_ah/api/explorer and I visit the insertQuote method. Remember that is the method that we secured and want to test out.

We simply provide the Quote Author and Message and click on Execute. If you have done things carefully and correctly till now, you will see an error pop up as shown below. It clearly states that you need to be authenticated.

cep-ep5-3

Note that, the Response is correctly thrown back as we had done in our code. We had thrown an UnauthorizedException and that is translated back into a HTTP 401 Status Code correctly as shown below.

cep-ep5-4

Since we are using the API Explorer client over here, we need to login over here. In the right corner, you will find a Toggle as shown below:

cep-ep5-5

Click on the Toggle switch to turn it ON. This brings up the typically OAuth dance sequence. The first popup shows the SCOPE that we had defined on our API. Remember the EMAIL_SCOPE constant. That is selected by default. Simply click on the Authorize button.

cep-ep5-6

This will bring up a Google login. Just login or select the Account (in case you have multiple Google Accounts). Complete the Login successfully and you will be back in the API explorer with the Toggle switched on to ON as shown below:

cep-ep5-7

Now, fire off the insertQuote method again. And this time, all is well. Notice in the POST Request HTTP Headers that the Authorization Header is generated by the API Explorer.

cep-ep5-8

This completes all the work right from generating a Client ID, specifying Client Id details in the methods that we want to secure and then testing it out via the API explorer.

Note: Did you notice that we have not used the Client Id that we generated in the first step. This will become clear in the next episode where we shall write our JavaScript Web client and use the Client Id.

Project Source Code

I have updated the source code for the MyAPIProject2. You can download the entire source code over here.

Hope you liked this episode of the Google Cloud Endpoints tutorial. Stay tuned for more episodes, where we shall see how to invoke our secure API methods from a JavaScript client and an Android client.

Google Cloud Endpoints Tutorial – Part 4

Welcome to Part 4 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

We are going to look at another client in this episode. This time, it will be a JavaScript client that we can use via the Google Java Script Client API that can interact with our Quotes Endpoint API.

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. Even if you do not want to load it, just follow along in the tutorial to see how to invoke the API in your HTML page via Java Script.

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. This environment is needed just that I can run the Endpoints API locally and test the Java Script client against it.
  • Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Revisiting the Quotes API

Let us recap quickly on what we have done so far. We have written a Quotes API hosted on Google App Engine that allows us to perform CRUD operations via a HTTP REST API. A Quote record contains a couple of attributes, the author and the famous quote that the author gave.

If you look at the API Methods, we had the following methods exposed:

Screen Shot 2014-01-12 at 4.21.42 PM

I will simply be writing the Java Script client in this episode and making sure that the App Engine project is up and running on my local machine.

Java Script Code in Action

Let us look at our HTML page in which we will invoke the Quotes Endpoint API via Java Script.

In a previous version of this post, I had demonstrated only the list Quotes method. Thanks to +Gerwin Sturm, who pointed out that there could be complications related to invoking the other REST methods (insert Quote, update Quote)  via the Google Javascript API client, I wanted to provide the code for all the operations.

So, we will be writing a test html page (apitest.html) that will provide functionality for all

  • Listing Quotes
  • Adding a New Quote
  • Updating a Quote
  • Deleting a Quote.

I have a few quotes present in the Datastore and the apitest.html page is shown below. I have retrieved all the Quotes when the List Quotes button is clicked, as shown below. I have 3 Quotes in my datastore currently and I am displaying the quote text, author and in square brackets at the end, I have the ID , which is provided here to make it a bit easier for us to perform operations for updating and deleting the quote, which will require an ID.

Screen Shot 2014-01-24 at 11.55.08 AM

The page listed above should be straightforward to understand. It has various sections to perform the different operations.

Client code

The full source listing for apitest.html is given below. Let us cover the important points:

  • The Quotes Endpoints API is available as a HTTP REST API and you can definitely use standard Ajax Java Script code to invoke the API to do the same.
  • To speed up things, Google has provided a Javascript API that is an easier way to access all the Google APIs and Google Cloud Endpoints is no exception. You should definitely check out the API reference.
  • The first thing we are going to do is load the Javascript API via the <script> tag that you will find at the end of the code listing.<script src=”https://apis.google.com/js/client.js?onload=init”></script&gt;
  • Once the file is loaded, we pass our init function that can be invoked.
  • The init method does an important thing. It invokes the gapi.client.load method that loads the client library interface to a particular API. The particular API in question is our Quotes API.
  • The method parameters for the gapi.client.load method is shown below (Refer to the docs too!)
    • name : This is the name of the API. In our case it is quoteendpoint. If you look at the Endpoint API source code, you will notice that the @API(name…) is equal to quoteendpoint.
    • version : This is the version of the API. It is v1 in our case.
    • callback : This is the function to be called once the API Interface is loaded.
    • API Root : This is the API Root URL i.e. protocol://hostname:port/_ah/api. Since we are running and testing it against the local host, it is http://localhost:8888/_ah/api
  • After the gapi.client.load method, you will find that we have created standard event handlers for all the 4 buttons that invoke the respective functions i.e. listQuotes(), insertQuote(), updateQuote() and deleteQuote().
  • The Google Client API is invoked in a standard fashion. In the listQuotes() method, you will notice that we are invoking gapi.client.quoteendpoint.listQuote().execute(…) method. One of the ways to figure out the different methods is also to use the Chrome Dev tools as shown below:
    Screen Shot 2014-01-18 at 6.52.42 PM
  • The callback method inside of the execute method, returns back the JSON result as we have seen before:
    Screen Shot 2014-01-18 at 6.51.45 PM
  • We simply iterate through the items and populate the div element with the results. In particular, we use the author and message attributes of each item.
  • For the insertQuote() method, we first retrieve the 2 attributes i.e. Author Name and Quote Text. One can do validations like empty values are not allowed, but we can leave that as an exercise for the reader. We create the Request Object for the insertQuote() method , which should look something like the following:
    { “author”:”…”, “message”: “…”} and then we simply invoke the gapi.client.quoteendpoint.insertQuote(<RequestObject>).execute(…) method
  • For the updateQuote(), we first retrieve the 3 attributes i.e. ID, Author Name and Quote Text.  We create the Request Object for the updateQuote() method , which should look something like the following:{ “id”: “…”, author”:”…”, “message”: “…”} and then we simply invoke the gapi.client.quoteendpoint.updateQuote(<RequestObject>).execute(…) method
  • For the deleteQuote(), we only need the ID We create the Request Object for the deleteQuote() method , which should look something like the following:{ “id”: “…”} and then we simply invoke the gapi.client.quoteendpoint.updateQuote(<RequestObject>).execute(…) method

Observations

  • You should play with the API explorer more for all the operations, so that you are aware of what HTTP Responses are being received for each of the operations. For e.g. in the case of a successful delete a 204 No Content is returned and so on. Understanding this will help you create the right kind of client messages that you can display to the user.
  • You should definitely visit the Cloud Endpoints generated code for your API. What I mean is that you will need to most likely modify the Datastore API code to make your API more robust and provide the correct HTTP Exceptions. As an example, before you attempt to delete a Quote, you might want to check for its existence. And if it does not exist, you might want to throw a 404. So look at your API from that angle to make it more solid.

Project Source Code

I have updated the source code for the MyAPIProject2, which is the same source as the one that we saw in Part 2, except that an additional file apitest.html has been added. You can download the entire source code over here.

Hope you liked this episode of the Google Cloud Endpoints tutorial.  Check out the next episode on how to secure your API.