req icon indicating copy to clipboard operation
req copied to clipboard

Issue with malformed `base_url`s

Open mxub opened this issue 2 years ago • 6 comments

Hey everyone,

I just ran into an issue where the following code results in a 404 error:

settings = Req.new(
  base_url: "https://api.apaleo.com/settings/v1",
  auth: {:bearer, access_token},
  headers: [
    "content-type": :"application/json",
  ]
)

Req.get!(settings, url: "/properties/TEST")

Thats because URI.merge("https://api.apaleo.com/settings/v1", "/properties/TEST") results in "https://api.apaleo.com/properties/TEST".

I think it should be mentioned somewhere that a trailing / in the :base_url an no leading one in the :url are less error prone.

Maybe the readme should feature that style?

mxub avatar Jul 03 '22 23:07 mxub

Thank you for the report. This is a bug, what you expected should work. A PR is appreciated.

wojtekmach avatar Jul 04 '22 05:07 wojtekmach

btw,

headers: [
  "content-type": :"application/json",
]

can be also written as:

headers: [
  "content-type": "application/json",
]

or

headers: [
  content_type: "application/json",
]

it is fine as is of course :)

wojtekmach avatar Jul 04 '22 05:07 wojtekmach

But what is the intended way? Would a simple

"https://api.apaleo.com/settings/v1" <> "/properties/TEST"

more sufficient than

URI.merge("https://api.apaleo.com/settings/v1", "/properties/TEST")

otherwise we should define the behavior beforehand and than implement it.

mxub avatar Jul 05 '22 09:07 mxub

not quite. If :url contains a full url (has schema), :base_url is ignored. That's why we went with URI.merge as it does it already.

wojtekmach avatar Jul 05 '22 10:07 wojtekmach

in terms of specifying the behaviour I'm thinking about something like this. wdyt?

base_url url result
https://a.com x https://a.com/x
https://a.com /x https://a.com/x
https://a.com/x y https://a.com/x/y
https://a.com/x /y https://a.com/x/y
https://a.com https://b.com https://b.com

but happy to make it stricter, reject some of the values, if that would make the implementation simpler and/or be more predictable.

wojtekmach avatar Jul 05 '22 10:07 wojtekmach

base_url url expected result URI result Comments
https://a.com x https://a.com/x https://a.com/x same
https://a.com /x https://a.com/x https://a.com/x same
https://a.com/x y https://a.com/x/y https://a.com/y trailing / missing
https://a.com/x/ y https://a.com/x/y https://a.com/x/y
https://a.com/x /y https://a.com/x/y https://a.com/y
https://a.com/x/ /y https://a.com/x/y https://a.com/y
https://a.com/x/y ../foo ? https://a.com/foo
https://a.com/x/y/ ../foo ? https://a.com/x/foo
https://a.com https://b.com https://b.com https://b.com same

I think we would win a lot by requiring the trailing / maybe even just appending it?

mxub avatar Jul 05 '22 11:07 mxub

Fixed in #132

wojtekmach avatar Sep 09 '22 06:09 wojtekmach