HTTP Annotations
These annotations define how Ktorgen maps Kotlin interfaces and methods into HTTP requests for Ktor Client.
Ktorgen’s HTTP annotations are inspired by Retrofit and Ktorfit, providing a familiar developer experience while maintaining:
- KMP compatibility
- Type safety
- Compile-time validation
HTTP Method Annotations
HTTP method annotations describe the type of HTTP request the generated function will perform.
@HTTP
Generic annotation for defining a custom HTTP method.
Can be used instead of specific method annotations (@GET, @POST, etc.).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
method |
String |
The HTTP method name (e.g. "TRACE"). |
Required |
path |
String |
Endpoint path relative to @KtorGen.basePath or Ktor default request. |
"" |
hasBody |
Boolean |
Whether this method allows a request body. | false |
Examples
Custom method
@HTTP(method = "PROPFIND", path = "meta", hasBody = false)
suspend fun getMetadata(): Metadata
Body with non-standard verb
@HTTP(method = "LINK", path = "relations", hasBody = true)
suspend fun linkUser(@Body data: RelationBody): Result
Standard HTTP Methods
Shortcut annotations for common HTTP methods.
Equivalent to using @HTTP(method = "...", path = "...", hasBody = ...).
Supported annotations:
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
path |
String |
Relative path appended to basePath. |
"" |
Examples
Basic GET
@GET("users/{id}")
suspend fun getUser(@Path id: Long): User
POST with body
@POST("users/new")
suspend fun createUser(@Body user: UserCreateRequest): Response<User>
Request Encoding Annotations
These annotations define how request data is encoded before being sent to the server.
@FormUrlEncoded
Marks a request body as application/x-www-form-urlencoded.
- Usually combined with
@Fieldor@FieldMap - This annotation can be omitted, as it is inferred automatically when those parameters are present
Examples
@FormUrlEncoded
@POST("login")
suspend fun login(
@Field("user") user: String,
@Field("pass") password: String
): Token
@FormUrlEncoded
@POST("register")
suspend fun register(@FieldMap data: Map<String, String>): ApiResponse
@Multipart
Marks a request as multipart/form-data.
- Combined with
@Partor@PartMap - Can also be omitted, as it is inferred from parameters
Examples
@Multipart
@POST("upload")
suspend fun uploadFile(@Part file: ByteArray): UploadResponse
@Multipart
@POST("profile")
suspend fun updateProfile(
@Part("avatar") image: File,
@Part("bio") bio: String
): Profile
Parameter Annotations
Parameter annotations describe how individual function parameters are mapped into the HTTP request.
@Body
Marks a parameter as the request body.
Rules
- Only one
@Bodyis allowed per function - Incompatible with:
@FormUrlEncoded@Multipart
Examples
@POST("users")
suspend fun create(@Body user: User): ApiResponse
@PUT("users/{id}")
suspend fun update(
@Path id: Long,
@Body update: UserUpdate
): ApiResponse
@Path
Replaces placeholders inside the request path.
Rules
- Names must match placeholders in the endpoint path.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
value |
String |
Placeholder name (without {}). |
Parameter name |
encoded |
Boolean |
Whether the value is already URL-encoded. | false |
Examples
@GET("users/{id}")
suspend fun get(@Path id: Int): User
@DELETE("users/{id}")
suspend fun delete(@Path("id") userId: Long)
@Query / @QueryMap
Appends query parameters to the URL.
Rules
nullvalues are omitted- Lists are supported
- Map keys cannot be null
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
value |
String |
Query parameter name | Parameter name |
encoded |
Boolean |
Whether the value is already encoded | false |
Examples
@GET("search")
suspend fun search(@Query("q") query: String): List<Result>
@GET("filter")
suspend fun filter(@QueryMap params: Map<String, String>): ApiResponse
@QueryName
Adds a query parameter without value, commonly used as flags.
| Parameter | Type | Description | Default |
|---|---|---|---|
encoded |
Boolean |
If true, the parameter is assumed to be pre-encoded. |
false |
Examples
@GET("users")
suspend fun all(@QueryName("active") active: Boolean = true): List<User>
@GET("posts")
suspend fun includeDrafts(
@QueryName includeDrafts: Boolean = false
): List<Post>
Header Annotations
Headers in Ktorgen are type-safe, repeatable, and validated at compile time.
Can a use a list of most used header names
defined in Header.Companion. Extracted from Http Headers Ktor
Contain common types of header Content-Type subdivide in objects as Type/Subtype. Extracted of ContentTypes Ktor
Contain commonly used Accept-Encoding values. Extracted of AcceptEncoding Ktor
See Http Headers MDN for more information.
@Header
Defines a static header at compile time.
Parameters
| Name | Type | Description |
|---|---|---|
name |
String |
Header name |
value |
String |
Header value |
Example
@Header("Content-Type", "application/json")
@Header(Header.Accept, Header.ContentType.Aplication.Json)
suspend fun request(): String
@HeaderParam
Defines a dynamic header provided at runtime.
| Parameter | Type | Description |
|---|---|---|
value |
String |
Header name. |
Examples
@GET("users")
suspend fun list(
@HeaderParam("Authorization") token: String,
@HeaderParam(Header.AcceptLanguage) lang: String
): List<User>
@HeaderMap
Adds multiple headers dynamically from a map.
Examples
@GET("secure")
suspend fun auth(@HeaderMap headers: Map<String, String>): Token
Form & Multipart Parameters
@Field / @FieldMap
Used inside @FormUrlEncoded request to send key-value pairs.
Example
@FormUrlEncoded
@POST("auth")
suspend fun login(
@Field("username") user: String,
@Field("password") pass: String
)
@Part / @PartMap
Used inside @Multipart requests to send files or multiple parts.
Important
If the type is PartData the value will be used directly with its content type.
Example
@Multipart
@POST("files")
suspend fun upload(@Part("file") file: File)
URL & Fragment Annotations
@Url
Replaces the entire request URL, ignoring basePath.
Can be a type of:
String- Ktor
Url - Ktor
UrlBuilder
More details, see Url.takeFrom
Rules:
- Cannot be used together with a path HTTP method annotations.
- Cannot be used together with
@Query,@QueryMap,@Path - Only one
@Urlis allowed per function.
Examples
@GET
suspend fun fromFullUrl(@Url url: String): ApiResponse
@Fragment
Injects URL fragments dynamically.
Rules
- Only one fragment per function
nullvalues are ommited
Examples
@GET("/users/{id}")
@Fragment("collection")
suspend fun fetchDynamic(@Path id: String): Response
@GET("/users/{id}")
suspend fun fetchDynamic(@Path id: String, @Fragment collection: String): Response
Cookie Annotation
@Cookie
Adds cookies to the request.
This annotation mirrors the behavior of HttpMessageBuilder.cookie,
but includes some adaptations due to annotation limitations:
nullvalues are not allowed. Instead, the following conventions are used:expiresTimestamp = -1L→ no expiration date.domain = ""andpath = ""→ no value assigned.extensionsis defined as an array ofPairStringfor type safety when mapping cookie extensions.
Important
If the Ktor Cookie plugin is installed, cookies defined here are ignored at runtime. For more information, refer to the official Ktor Client Request - Cookies documentation.
Rules:
- The value of the cookie is required in the function target.
Example
@Cookie(
name = "session_id",
value = "abc123",
maxAge = 3600,
secure = true,
httpOnly = true,
extensions = [Cookie.PairString("SameSite", "Strict")],
)
@GET
suspend fun myRequest(
@Cookie("yummy_cookie") flavor: String
): SecureResponse
Tag Annotation
@Tag
Adds metadata to requests, useful for interceptors, logging, or custom plugins as AttributeKey.
Rules
nullvalues are ommited.
Example
@POST("upload")
suspend fun upload(
@Body file: File,
@Tag("UploadInterceptor") interceptor: String,
@Tag tag: String?
)
Deprecated Annotations
@Streaming
@StreamingDeprecated.
Use return types like:
HttpResponseByteReadChannelByteArrayString
See Return Types documentation for more information.
@Headers
@HeadersDeprecated. This is only for easy migration from other libraries, using this doesn't generate code
From
@Headers("Content-Type: application/json", "Accept: application/json")
@Header(Header.ContentType, Header.ContentTypes.Application.Json)
@Header("Accept", "application/json)
See Header annotations for more information.
Summary
Ktorgen’s HTTP annotations:
- Follow Retrofit semantics
- Are KMP-compatible
- Are type-safe and repeatable
- Integrate directly with Ktor Client
To migrate from Retrofit:
import io.github.kingg22.ktorgen.http.*
And you're done 🚀