I have a Play application with a POST route which will act as a RESTful API.
Whats the best way to get POST data within a controller? As you can see from my controller I have attempted this, however it doesn't appear to work correctly.
Routes:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
GET /api/getMessages controllers.Application.getMessages()
POST /api/createMessage controllers.Application.createMessages()
Controller:
package controllers;
import play.*;
import play.mvc.*;
import static play.libs.Json.toJson;
import java.util.Map;
import models.*;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result createMessages(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
String from = values.get("from")[0];
String subject = values.get("subject")[0];
String message = values.get("message")[0];
Message.create(from, subject, message);
return ok(toJson("ok"));
}
public static Result getMessages(){
return ok(toJson(Message.all()));
}
}
Request:
Request Url: http://localhost:9000/api/createMessage
Request Method: POST
Status Code: 400
Params: {
"from": "[email protected]",
"subject": "Hello",
"message": "World"
}