Google App Engine

Writing the API: A Simple POST

In this part of the tutorial, you'll add a simple POST to the backend API that you created previously.

Adding a POST method

  1. In your Greetings.java file created previously in project directory /src/main/java/com/google/appengine/samples/helloendpoints, add the following import:

    import com.google.api.server.spi.config.ApiMethod;
    
  2. In the Greetings class, add the following code:

    @ApiMethod(name = "greetings.multiply", httpMethod = "post")
    public HelloGreeting insertGreeting(@Named("times") Integer times, HelloGreeting greeting) {
      HelloGreeting response = new HelloGreeting();
      StringBuilder responseBuilder = new StringBuilder();
      for (int i = 0; i < times; i++) {
        responseBuilder.append(greeting.getMessage());
      }
      response.setMessage(responseBuilder.toString());
      return response;
    }
    
  3. Run the backend you just created by invoking the command

    mvn appengine:devserver
    
  4. When the backend builds and loads successfully, use the browser to visit the URL

    http://localhost:8080/_ah/api/explorer
    
  5. In the API Explorer, after you click helloworld API, notice that the list now also contains the new method. Click helloworld.greetings.multiply to display the Explorer form for it:
    greetings.multiply

  6. In the form's times textbox, supply the number of times you want the POSTed message to be echoed in the response, for example, 3.

  7. Click inside the Request body control, click add a property > message, add the text message Charles Darnay, then click Execute.

  8. In the Response, you'll see the success message and the message " Charles Darnay Charles Darnay Charles Darnay".

Code summary

Remember that @ApiMethod is optional: we are using it here only to supply our own name for the method. If we don't supply this, the framework will supply a generated default name.

In the code, notice the import of com.google.api.server.spi.config.ApiMethod, which is required since we are annotating a method. We are using this to supply a method name, but other attributes are available. For more information, see @ApiMethod: Method-Scoped Annotations or the Javadoc for @ApiMethod.

Next...

Next, we'll add a method that is access-restricted by OAuth 2.0.

Continue to Adding a Method Protected by OAuth 2.0.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.