0

I want to set a url as encoded url to REST API. The url I want to my route to look like this

Required: https://localhost:3000/api/v1/articles?url=https%3A%2F%2Frepository.dri.ie%2Fcatalog%2F5999pn33w&format=json

In the routes.rb I tried to set the route like this:

namespace 'api' do
 namespace 'v1' do
  resources :articles
  get 'articles/*url'  => 'articles#show' 
 end
end     

so my route look like this

http://localhost:3000/api/v1/articles/https://repository.dri.ie/catalog/5999pn33w

how can I make the url passed as encoded url?

max
  • 96,212
  • 14
  • 104
  • 165
Muzi
  • 3
  • 4
  • Does this answer your question? [Route parameter with slash "/" in URL](https://stackoverflow.com/questions/30972578/route-parameter-with-slash-in-url) – Tom Lord Sep 17 '20 at 08:24
  • Granted that answer isn't using ruby/rails, but the key part is about URL encoding. You can't just put un-encoded forward slashes into the route's path, or they will be treated as separate sections of the path. – Tom Lord Sep 17 '20 at 08:33

1 Answers1

2

You have missidentified the issue here as it has nothing to do with URL encoding. Rails doesn't care about the contents of the query string when matching routes. It just matches the request by path and method.

Thus a request for https://localhost:3000/api/v1/articles?url=https%3A%2F%2Frepository.dri.ie%2Fcatalog%2F5999pn33w&format=json will alway match the index route defined by resources :articles. Remember also that routes have priority in the order they are defined.

What you need to do instead is create a route that matches /articles with a constraint:

Rails.application.routes.draw do
  # Custom route to match /articles?url=xxx
  get 'articles',
    to: 'articles#show',
    constraints: ->(request){ request.query_parameters["url"].present? }
  # this must come after the custom route
  resources :articles
end
max
  • 96,212
  • 14
  • 104
  • 165