In Retrofit, how do @Path, @Query, @QueryMap and @Body map method arguments onto a request, and how does each treat null?
answer
- template blocks versus appended pairs
- null skipped in one place only
- maps refuse null entries
- a list repeats the name
- body goes through a converter
basics
~20 s@Path fills a {block} in the annotation's relative URL, @Query appends name=value pairs, @QueryMap appends a whole map and @Body becomes the converted request body. Of the four, only @Query skips null; null @Path, @Body or map entries throw IllegalArgumentException.
solid answer
~40 sRetrofit reads the method annotation's relative URL, then applies each parameter in order. `@Path("projectId")` replaces `{projectId}`, URL-encoding the value so a `/` becomes `%2F`. `@Query("label")` appends `label=...`; a `null` value is skipped and a `List` or array repeats the parameter once per non-null item. `@QueryMap` appends every entry, but a `null` map, key or value throws `IllegalArgumentException`, so filter the map first. `@Body` hands the object to a converter to build the request body; it may not be `null`, there can be only one, and a method without a request body such as `@GET` rejects it. A `null` `@Path` value also throws, because there is nothing sensible to put in the URL.
code
kotlin · 21 linesinterface IssueService {
@GET("projects/{projectId}/issues")
suspend fun searchIssues(
@Path("projectId") projectId: String,
@Query("assignee") assignee: String?,
@Query("label") labels: List<String>,
@QueryMap filters: Map<String, String>,
): List<IssueSummary>
@GET("projects/{projectId}/issues/{issueId}")
suspend fun issue(
@Path("projectId") projectId: String,
@Path("issueId") issueId: Long,
): Issue
@POST("projects/{projectId}/issues")
suspend fun createIssue(
@Path("projectId") projectId: String,
@Body draft: IssueDraft,
): Issue
}go deeper
Recall what each of the four annotations fills: a path block, a query pair, many query pairs, or the body. Know that a null @Query vanishes from the URL.
Explain the null rules per annotation, list expansion into repeated pairs, path encoding of slashes, and why a replace block in the query string is rejected.
Show you build filter maps without nulls, keep untrusted ids in @Path with default encoding, and know the path-traversal guard and the unbound-block gap.
Be ready to set team conventions: optional filters as nullable @Query parameters, @QueryMap only for genuinely open-ended filters, and ids always passed through @Path.
## How a service method becomes a request Retrofit turns a **service interface** into requests. Every method carries one HTTP method annotation such as `@GET` or `@POST` whose value is a **relative URL**: a path, optionally with a static query string, resolved later against the `baseUrl` the `Retrofit.Builder` was given. Every parameter carries a Retrofit annotation that says which part of the request it fills. When the method is called, Retrofit applies the parameters **in declaration order** to a request builder, then hands the finished `okhttp3.Request` to OkHttp. Take an issue tracker that lists a project's issues with search filters and creates new issues: - `GET projects/{projectId}/issues?label=bug&label=crash&sort=updated` - `POST projects/{projectId}/issues` with a JSON body ## The four annotations | Annotation | Fills | `null` argument | Collections | |---|---|---|---| | `@Path("name")` | a `{name}` block in the relative URL | throws `IllegalArgumentException` | not expanded | | `@Query("name")` | one `name=value` pair | **skipped** | one pair per non-null item of a `List` or array | | `@QueryMap` | one pair per map entry | a `null` map, key or value throws | the map is the collection | | `@Body` | the request body, via a converter | throws `IllegalArgumentException` | only one `@Body` per method | **`@Path`** values are turned into strings by a string converter (or `toString()`), then **percent-encoded** for a path segment. With the default `encoded = false`, a `/` becomes `%2F` and `%` becomes `%25`, so the value stays inside one segment. `encoded = true` passes slashes and existing escapes through. Block names must start with a letter and contain only letters, digits, `_` and `-`. **`@Query`** is the everyday filter. A nullable Kotlin parameter (`assignee: String?`) is the idiom for an optional filter: pass `null` and the pair disappears from the URL. Passing an empty string is different: it sends `assignee=` with no value. **`@QueryMap`** suits a filter screen whose keys vary. Its contract is stricter than `@Query`: the javadoc says a `null` map, key or value is not allowed, and the request fails with a message such as `Query map contained null value for key 'milestone'.` Build the map with only the filters the user set. **`@Body`** is converted by the first registered converter that accepts the type (converters have their own lesson). A `RequestBody` can always be passed raw. ## Rules Retrofit enforces 1. A `{block}` inside the annotation's **query string** is rejected: `@GET("issues?state={state}")` fails with "URL query string ... must not have replace block. For dynamic query parameters use @Query." A static query (`issues?state=open`) is fine. 2. A `@Path` parameter must not come after a `@Query`, `@QueryName` or `@QueryMap` parameter, and its name must appear in the URL template, or parsing fails with `URL "..." does not contain "{name}".` 3. `@Body` on a method without a request body, such as `@GET` or `@DELETE`, fails with "Non-body HTTP method cannot contain @Body." (`@HTTP` with `hasBody = true` is the way to send a body with `DELETE`.) 4. Since Retrofit 2.5.0, a `@Path` value that leaves a whole path segment of `.` or `..` (including `%2e`) throws, so untrusted input cannot walk the URL up a level. 5. The check runs one way only: Retrofit verifies that each `@Path` name exists in the template, but it does not verify that each `{block}` has a `@Path`. An unbound block goes out unfilled in the URL. ## Worked call With the interface in the example below, `searchIssues("ANDROID", null, listOf("bug", "crash"), mapOf("sort" to "updated"))` produces `projects/ANDROID/issues?label=bug&label=crash&sort=updated` relative to the base URL: - the `null` assignee left no trace; - the list produced two `label` pairs, in list order; - the map entries were appended after them, because parameters are applied in order. Calling `issue(projectId = "ANDROID", issueId = 42)` fills both blocks. Passing a project id of `"mobile/android"` would produce `mobile%2Fandroid`, one segment, which is usually what the server expects for an opaque id. ## What interviewers listen for - Knowing **which annotation skips null** and which throws, rather than assuming all of them behave like `@Query`. - Knowing that a list maps to **repeated parameters**, not a comma-joined value; if the server wants `label=bug,crash`, join the values yourself. - Using `@Path` only for path segments and `@Query` for anything after `?`. - Treating `@Body` as a converter's job, not something Retrofit serialises by itself.
- What does Retrofit do with a @Path value that contains a slash or is just two dots?With the default `encoded = false`, a `/` is percent-encoded as `%2F`, so the value stays one segment; `encoded = true` lets the slash through and splits it into segments. Separately, since Retrofit 2.5.0 a value that produces a whole `.` or `..` segment, including `%2e`, throws `IllegalArgumentException`, so input like `..` cannot turn `DELETE issues/{id}` into a request against the parent path.
- Does the order of parameters in a Retrofit method matter?Yes, in two ways. Parameters are applied in declaration order, so query pairs appear in that order. And Retrofit rejects a `@Path` or `@Url` parameter declared after a `@Query`, `@QueryName` or `@QueryMap` with an `IllegalArgumentException` when it parses the method, so path-shaping parameters come first.
- A null @Path value is simply left out of the URL.
- A null value inside a @QueryMap is skipped like a null @Query.
- @Query cannot take a list; values must be comma-joined by hand.
- Writing {state} in the annotation's query string works like @Path.
- @Body can be added to any method, including @GET.
Assumes Retrofit 3.0.0; the @Path guard against . and .. segments has been in place since Retrofit 2.5.0.