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
-
In your
Greetings.javafile 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; -
In the
Greetingsclass, 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; } -
Run the backend you just created by invoking the command
mvn appengine:devserver -
When the backend builds and loads successfully, use the browser to visit the URL
http://localhost:8080/_ah/api/explorer -
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:

-
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.
-
Click inside the Request body control, click add a property > message, add the text message Charles Darnay, then click Execute.
-
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, see @ApiMethod: Method-Scoped Annotations or the
Javadoc for @ApiMethod.
Important: Notice the use of the HelloGreeting 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.