Route with hyphen (-) cast error

Hello I’m trying to create a custom route like this:

{
  "method": "GET",
  "path": "/articles/draft-to-publish/",
  "handler": "article.draftToPublish",
  "config": {
    "policies": []
  }
}

inside my draftToPublish I only have a console.log .

But when calling the endpoint with postman i get a error 500:

error CastError: Cast to ObjectId failed for value “draft-to-publish” at path “_id” for model “article”

But if I change the path to something like this it works perfect:

/articles/draft/to/publish/

Whats going on here? Thank you very much!

That’s because you already have an identical route for findOne:

{
  "method": "GET",
  "path": "/articles/:id",
  "handler": "article.findOne",
  "config": {
    "policies": []
  }
}

You should create a different route for your needs. When you are accessing route /articles/draft-to-publish it actually calls the findOne controller from the above example.

1 Like

Koa (what we use in the backend of strapi) along with the koa-router uses routes based on a regex match, so to use this endpoint it needs to be above the one that @sunnyson mentioned. (Your error was because it assumed draft-to-publish was actually an :id).

So you can move your custom route above that one, or make it 3rd level endpoint like /articles/function/draft-to-publish or something (ugly example but making it clear what I mean)

1 Like