Why does Retrofit.Builder reject a baseUrl such as https://tracker.example.com/api/v2, and how do endpoint paths resolve against a base URL?
answer
- web-link resolution rules
- last segment gets replaced
- leading slash means absolute
- full URL swaps host
basics
~20 sA baseUrl with a path must end in a slash, or relative endpoints would replace its last segment; Retrofit.Builder throws IllegalArgumentException otherwise. Endpoints resolve like web links: relative paths append, a leading slash keeps only the host, a full URL replaces it.
solid answer
~40 sRetrofit resolves each endpoint against the base with OkHttp's `HttpUrl.resolve`, which behaves like an `<a href>` link on a page. Under those rules, a relative reference replaces the **last** path segment of the base, so `https://tracker.example.com/api/v2` plus `issues` would give `/api/issues` and silently lose `v2`. That is why `Retrofit.Builder.baseUrl` throws `IllegalArgumentException: baseUrl must end in /` when the base has a path without a trailing slash. With a slash, `issues` resolves to `/api/v2/issues`. A leading slash makes the endpoint absolute, so `/issues` drops `/api/v2/` and keeps only the host, a classic source of 404s. A full URL in the annotation replaces scheme and host; a `//host/path` reference keeps the base's scheme.
code
kotlin · 14 linesval retrofit = Retrofit.Builder()
.baseUrl("https://tracker.example.com/api/v2/")
.addConverterFactory(converterFactory)
.build()
interface IssueService {
// https://tracker.example.com/api/v2/projects/{projectId}/issues
@GET("projects/{projectId}/issues")
suspend fun issues(@Path("projectId") projectId: String): List<IssueSummary>
// https://tracker.example.com/health (the leading slash drops /api/v2/)
@GET("/health")
suspend fun health(): Unit
}go deeper
Remember that a base URL with a path ends in a slash and that endpoints should not start with one if they belong under that path.
Explain link-style resolution: the last segment is replaced, a leading slash keeps only the host, a full URL replaces scheme and host.
Diagnose a fleet of 404s or doubled prefixes from the resolution rules, and know which mistake the builder catches and which it lets through.
Set a convention the whole codebase follows: the base holds the API prefix, endpoints are always relative, and environment switching rebuilds the client.
## The base URL and the relative URL A Retrofit client has one **base URL**, set with `Retrofit.Builder().baseUrl(...)`, and every service method carries a **relative URL** in its HTTP method annotation, for example `@GET("issues/{issueId}")`. When a call is made, Retrofit combines the two with OkHttp's `HttpUrl.resolve`. The Retrofit javadoc describes this as matching an `<a href="">` link on a website resolving against the current page, which is the standard URL reference resolution browsers apply to links. Calling `build()` with no base URL at all fails with `IllegalStateException: Base URL required.` ## Why the trailing slash is enforced Under link resolution, the base URL's path is treated like a directory only when it ends in `/`. Without the slash, the **last segment is a file name** and a relative reference replaces it: | Base URL | Endpoint | Result | |---|---|---| | `https://tracker.example.com/api/v2/` | `issues` | `https://tracker.example.com/api/v2/issues` | | `https://tracker.example.com/api/v2` | `issues` | `https://tracker.example.com/api/issues` | The second row is a silent bug: the request goes to the wrong version of the API. Retrofit refuses to build it. `baseUrl(HttpUrl)` checks that the last path segment is empty and otherwise throws: ``` IllegalArgumentException: baseUrl must end in /: https://tracker.example.com/api/v2 ``` A host-only base such as `https://tracker.example.com` is accepted, because `HttpUrl` normalises it to the path `/`, whose last segment is already empty. ## The four shapes an endpoint can take 1. **Relative path** (`issues/42`): appended to the base path. This is the normal case and keeps the API prefix. 2. **Leading slash** (`/issues/42`): **absolute path**. Only the base's scheme, host and port survive; `/api/v2/` is dropped. Retrofit does not warn about this, because it is legitimate when a server exposes something outside the API prefix. 3. **Full URL** (`https://files.example.com/a/b`): replaces the base's scheme and host as well as the path. 4. **Scheme-relative URL** (`//files.example.com/a/b`): replaces the host but keeps the base's scheme, so an `http` base stays `http`. The same rules apply to a URL passed at runtime through `@Url`, so a pagination link or a pre-signed download link returned by the server resolves exactly as it would in a browser. ## Common failures and how to spot them - **A 404 on every call after adding an API version prefix.** The endpoints were written with leading slashes, so `/issues` ignores the new `/api/v2/` prefix. Remove the leading slashes. - **A crash on startup after moving the base URL into build config.** The value lost its trailing slash, and `baseUrl` threw. Keep the slash in the configured value, or add it when reading the config. - **Doubled or missing segments.** Mixing a prefix in the base with the same prefix in some annotations gives `api/v2/api/v2/issues`. Decide that the base holds the prefix and endpoints never repeat it. - **Environment switching.** A `Retrofit` instance's base URL is fixed. For a debug menu that switches environments, build a new instance with `retrofit.newBuilder().baseUrl(...).build()` and recreate the services from it; rewriting the host per request is done in the OkHttp client instead, which has its own lesson. ## Where the resolution happens Retrofit combines the two URLs while it builds each request, after the `@Path` blocks have been filled: 1. If the method has no query parameters, Retrofit calls `baseUrl.resolve(relativeUrl)` once the path is complete. 2. If it has `@Query` or `@QueryMap` parameters, the first one triggers `baseUrl.newBuilder(relativeUrl)`, which applies the same resolution and then appends the pairs. 3. If OkHttp cannot produce a valid URL from the pair, Retrofit throws `IllegalArgumentException` with `Malformed URL. Base: ..., Relative: ...`, naming both halves so the bad one is easy to find. Because the base is an `HttpUrl`, it has already been parsed and normalised when the builder accepted it; an invalid base fails earlier, inside `baseUrl(String)`, rather than on the first request. `baseUrl` also accepts an `HttpUrl` or a `java.net.URL` directly, and all three overloads apply the same trailing-slash check. ## Worked example With `baseUrl("https://tracker.example.com/api/v2/")`: - `@GET("projects/{projectId}/issues")` resolves to `https://tracker.example.com/api/v2/projects/ANDROID/issues`. - `@GET("/health")` resolves to `https://tracker.example.com/health`, outside the versioned API. - `@GET("https://status.example.com/summary")` goes to another host entirely. ## What a good answer shows - It names the **resolution rule**, not just "add a slash": the last segment is replaced unless the path ends in `/`. - It knows the slash rule is **enforced** by the builder, while the leading-slash pitfall is **not** detected. - It treats an absolute or full URL in an annotation as a deliberate choice, not an accident.
- Does Retrofit accept https://tracker.example.com, with no slash at all, as a base URL?Yes. `HttpUrl` normalises a host-only URL to the path `/`, whose last segment is already empty, so the trailing-slash check passes. The check only fails when the base has a non-empty last path segment, such as `https://tracker.example.com/api/v2`.
- How do you point a running app at a different environment?A `Retrofit` instance's base URL cannot change. Build a new instance with `retrofit.newBuilder().baseUrl(newBase).build()` and create the services from it, typically when the debug environment setting changes. Rewriting the host on each request belongs in the OkHttp client rather than in Retrofit.
A base URL is a folder path; without the trailing slash it reads as a file inside the parent folder, so anything you add lands next to that file instead of inside the folder.
- The trailing slash is cosmetic; Retrofit adds one if missing.
- A leading slash on an endpoint is appended to the base path.
- Retrofit concatenates the base and endpoint strings directly.
- A full URL in an annotation is ignored in favour of the baseUrl.
- The base URL can be changed on an existing Retrofit instance.