Google App Engine
Feedback on this document

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. This illustrates the use of @ApiMethod.

Adding a POST method

  1. In your Greetings.java file created previously in project directory /src/main/java/com/google/devrel/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 Greeting insertGreeting(@Named("times") Integer times, Greeting greeting) {
          Greeting response = new Greeting();
          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

  1. 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.

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

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

Code summary

In the code, notice the import of com.google.api.server.spi.config.ApiMethod, which is required since we are annotating a method. Notice that because we use this annotation, we can use any name we want, instead of limiting ourselves to the nomenclature of a class name prepended with get, list, delete, or update, along with corresponding fixed HTTP methods. For a list of the attributes available for @ApiMethod, see @ApiMethod: Method-Scoped Annotations.

Important: Notice the use of the Greeting JavaBean class. For Endpoints, the POST body must be a JavaBean: using scalars like String or Integer will result in errors.

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.