Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting CRUD paths in akka-http directives

I am just starting with Scala and Akka. I am writing a small REST service. I am trying to create following paths:

  • GET localhost:8080/api/my-service (return collection of resources)
  • GET localhost:8080/api/my-service/6 (return resource with specified id)
  • POST localhost:8080/api/my-service (create new resource with data in body)
  • UPDATE localhost:8080/api/my-service/4 (update requested resource with data in body)
  • DELETE localhost:8080/api/my-service/5 (deletes resource with specified id)

I have managed to create nested paths, but however only GET for fetching the collections (first example in bullet points) is returning the results. Example GET with id in the path is returning The requested resource could not be found. I have tried many different variations, but nothing seems to work.

Here is excerpt of my routes:

val routes = {
    logRequestResult("my-service-api") {
        pathPrefix("api") {
            path("my-service") {
                get {
                    pathEndOrSingleSlash {
                        complete("end of the story")
                    } ~
                    pathPrefix(IntNumber) { id =>
                        complete("Id: %d".format(id))
                    }
                } ~
                (post & pathEndOrSingleSlash & entity(as[MyResource])) { myResourceBody =>
                    // do something ...
                }
            }
        }
    }
}

I have already checked many solutions on the web and some tests from Akka itself, but somehow I am missing here something.

like image 395
daniyel Avatar asked Jul 21 '17 08:07

daniyel


1 Answers

I found a solution. Problem was in path("my-service") part. I've changed it to pathPrefix("my-service") and now both GET paths are working.

So the correct route setup should look something like this.

val routes = {
    logRequestResult("my-service-api") {
        pathPrefix("api") {
            pathPrefix("my-service") {
                get {
                    pathEndOrSingleSlash {
                        complete("end of the story")
                    } ~
                    pathPrefix(IntNumber) { id =>
                        complete("Id: %d".format(id))
                    }
                } ~
                (post & pathEndOrSingleSlash & entity(as[MyResource])) { myResourceBody =>
                    // do something ...
                }
            }
        }
    }
}
like image 60
daniyel Avatar answered Oct 11 '22 13:10

daniyel