Mike Henke
Mike Henke

Reputation: 643

Play Framework Scala REST DELETE

I'm trying to figure out how to use the REST DELETE function using the Play Framework. Here's what I have:

My Model:

case class Task(id: Int, name: String, description: String, group: String)

object Task {

var list: List[Task] = Nil

def save(task: Task) = {
    list = list ::: List(task)
}

def all(): List[Task] = Nil

def delete(id: Int){
    val b = list.toBuffer
    b.remove(id)
    b.toArray
}

Here's what I have in my Controller for delete:

def deleteTask(id: Int) = Action {
    Task.delete(id)
    Ok
}

and my route:

DELETE /tasks/id controllers.TaskController.deleteTask(id: Int)

Forgot to mention my problem! How can I run this to test and make sure that it is working? I use the command:

curl --include --request POST --header "content-type: application/json" --data '{"id":4, "name": "test5", "description": "testdesc1","group": "groupc"}' http://localhost:9000/tasks

and it posts correctly. How can I do a similar action with DELETE?

Upvotes: 1

Views: 1972

Answers (1)

Anton Sarov
Anton Sarov

Reputation: 3748

Your DELETE request is not defined properly right now. It should go DELETE /tasks/:id if you want to have the id as a parameter

.

The problem in your Scala code is on line b.remove(id) - in this case b is actually from type BufferLike and the remove method does not do what you use it for. It actually removes the element at the specified index and not the element which you provide. So if you provide id=4 then it is going to try to remove the 5th element, and fail with an IndexOutOfBoundsException which is a Runtime exception which leads to the error page you are receiving. You can just use the diff method on List instead, like this: val newList = list diff List(id)

You have specified it already in your routes file: you have defined a DELETE request - this means that your curl request should also be a DELETE one:

curl -X DELETE "http://localhost:9000/tasks/4"

There is no body to post when using DELETE - you just specify the ID of the resource you would like to delete.

Bonus: consider returning some other status like HTTP 204 - it is more intuitive when dealing with deletion

Upvotes: 3

Related Questions