Ktorfit is a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit
Ktorfit is a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit
When you find unexpected behaviour please write an issue
Last update: October 8, 2023
\ No newline at end of file
diff --git a/search/search_index.json b/search/search_index.json
index 2c075541e..1c9d96335 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Overview","text":"Ktorfit"},{"location":"#introduction","title":"Introduction","text":"
Ktorfit is a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit
From now on with every Ktorfit release there will also be a Gradle plugin with the same version. That means that drop you can drop the Gradle extension block where you previously set the version number and just bump the number of the Gradle plugin. https://foso.github.io/Ktorfit/installation/
plugins {\nid(\"de.jensklingenberg.ktorfit\") version \"1.7.0\"\n}\n
"},{"location":"CHANGELOG/#143-2023-07-13","title":"1.4.3 - 2023-07-13","text":""},{"location":"CHANGELOG/#fixed_1","title":"Fixed","text":""},{"location":"CHANGELOG/#372-crash-with-xiaomi-on-create-ktorfitbuilder-by-princeparadoxes","title":"372 Crash with Xiaomi on create Ktorfit.Builder by @princeparadoxes","text":""},{"location":"CHANGELOG/#142-2023-06-25","title":"1.4.2 - 2023-06-25","text":""},{"location":"CHANGELOG/#fixed_2","title":"Fixed","text":""},{"location":"CHANGELOG/#323-code-generation-issue-for-multipart-formurlencoded-by-ph1ll1pp","title":"323 Code generation issue for @Multipart / @FormUrlEncoded by @Ph1ll1pp","text":""},{"location":"CHANGELOG/#141-2023-06-03","title":"1.4.1 - 2023-06-03","text":""},{"location":"CHANGELOG/#changed_5","title":"Changed","text":"
Upgrade dependencies: Ktor 2.3.1
"},{"location":"CHANGELOG/#fixed_3","title":"Fixed","text":""},{"location":"CHANGELOG/#236-parsing-error-for-listarray","title":"236 Parsing error for list/array","text":""},{"location":"CHANGELOG/#140-2023-05-27","title":"1.4.0 - 2023-05-27","text":""},{"location":"CHANGELOG/#added_2","title":"Added","text":"
e.g.
interface ExampleApi{\nsuspend fun getUser(): Response<User>\n}\n\nval user = userKtorfit.create<ExampleApi>().getUser()\n\nif(user.isSuccessful){\nuser.body()\n}else{\nuser.errorBody()\n}\n
Ktorfit is now using converters factories to apply the converters, similar to Retrofit see more here https://foso.github.io/Ktorfit/converters/converters/
TypeData now has a field \u201ctypeInfo\u201d can be used to convert the Ktor HttpResponse body to the wanted type
CallConverterFactory for replacement of CallResponseConverter
FlowConverterFactory for replacement of FlowResponseConverter
Added support for targets: macosArm64, tvosArm64, tvosX64, tvosSimulatorArm64, watchosSimulatorArm64 #315
"},{"location":"CHANGELOG/#85-added-a-response-class-that-can-be-used-as-a-wrapper-around-the-api-response-the-converter-for-it-is-automatically-applied-thx-to-vovahost-datl4g","title":"85 Added a Response class that can be used as a wrapper around the API Response, the converter for it is automatically applied. thx to @vovahost, @DATL4G","text":""},{"location":"CHANGELOG/#changed_6","title":"Changed","text":"
Optimized generated code, the generated code that is used for a request will now directly set the Ktor code instead of delegating it to a Ktorfit class. This will make the code easier to understand.
From now on there are two versions of the ktorfit-lib.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib\u201d will stay like before and add the platform client dependencies for the clients.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib-light\u201d this will only add the client core dependency and not the platform dependencies for the clients. This will give you more control over the used clients, but you have to add them yourself. https://ktor.io/docs/http-client-engines.html Everything else is the same as \u201cktorfit-lib\u201d
From now on there are two versions of the ktorfit-lib.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib\u201d will stay like before and add the platform client dependencies for the clients.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib-light\u201d this will only add the client core dependency and not the platform dependencies for the clients. This will give you more control over the used clients, but you have to add them yourself. https://ktor.io/docs/http-client-engines.html Everything else is the same as \u201cktorfit-lib\u201d
kotlinx.coroutines.JobCancellationException: Parent job is Completed #70
\ud83d\udca5 Breaking changes
reverted the api of converters to the state of beta13, see #71
when you are updating from beta13, this is the only change to converters: returnTypeName is replaced through typeData, you can use typeData.qualifiedName to get the same value as returnTypeName
NEW: - Query parameters can now be nullable, null values will be ignored in requests - Function return types can now be nullable
FIX: - Url annotation not resolved correctly #65
BREAKING CHANGES: - Changed naming of Converters:
SuspendResponseConverter:
is now called RequestConverter
the wrapSuspendResponse is now called convertRequest.
returnTypeName is replaced through typeData, you can use typeData.qualifiedName to get the same value as returnTypeName RequestConverter need to be added with the requestConverter() on your Ktorfit object.
https://foso.github.io/Ktorfit/requestconverter/
ResponseConverters:
returnTypeName is replaced through typeData, you can use typeData.qualifiedName to get the same value as returnTypeName https://foso.github.io/Ktorfit/responseconverter/
wrapResponse from SuspendResponseConverter got renamed to wrapSuspendResponse. This add the possibility to have ResponseConverter and SuspendResponseConverter implemented in the same class.
throw compiler time error when you use @Path without the corresponding value inside the relative url path
every generated implementation class of an interface that Ktorfit generates will now contain a \u201ccreate\u201d ext function that can be used instead of the generic create() function e.g. Let\u2019s say you have a interface GithubService, then you can create an instance like this:
val ktorfit = ktorfit {\nbaseUrl(\"http://example.com/\")\n}.create<GithubService>()\n
or this
val ktorfit = ktorfit {\nbaseUrl(\"http://example.com/\")\n}.createGithubService()\n
By default, IntelliJ/Android Studio can\u2019t find the generated code, you need to add the KSP generated folder to the sourcesets like this: (See more here: https://kotlinlang.org/docs/ksp-quickstart.html#make-ide-aware-of-generated-code)
Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Definitions.
\u201cLicense\u201d shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
\u201cLicensor\u201d shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
\u201cLegal Entity\u201d shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \u201ccontrol\u201d means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
\u201cYou\u201d (or \u201cYour\u201d) shall mean an individual or Legal Entity exercising permissions granted by this License.
\u201cSource\u201d form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
\u201cObject\u201d form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
\u201cWork\u201d shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
\u201cDerivative Works\u201d shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
\u201cContribution\u201d shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \u201csubmitted\u201d means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \u201cNot a Contribution.\u201d
\u201cContributor\u201d shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
\u00a9 You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a \u201cNOTICE\u201d text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n
Copyright 2022 Jens Klingenberg
Licensed under the Apache License, Version 2.0 (the \u201cLicense\u201d); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0\n
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
"},{"location":"architecture/","title":"How Ktorfit works under the hood","text":"
Ktorfit consists of three main components KSP-Plugin, Compiler plugin and the Ktorfit lib
package com.example\n\nimport com.example.model.People\nimport de.jensklingenberg.ktorfit.http.GET\n\ninterface ExampleApi {\n@GET(\"/test\")\nsuspend fun exampleGet(): People\n}\n
Let`s say we have a interface like this.
At compile time Ktorfit/KSP checks for all functions that are annotated with Ktorfit annotations like @GET.
Then it looks at the parent interfaces of that functions and generates, the source code of a Kotlin class that implements the interface. The classes are named like the interfaces but with an underscore at the beginning and \u201cImpl\u201d at the end, and they have the same package as the interfaces. In this case a class named _ExampleApiImpl will be generated. The class will also implement KtorfitService. The setClient() function will be used to add the http client at runtime.
@OptIn(InternalKtorfitApi::class)\npublic class _ExampleApiImpl : ExampleApi, KtorfitService {\npublic override lateinit var ktorfitClient: Client\n\npublic override suspend fun exampleGet(): String {\nval _ext: HttpRequestBuilder.() -> Unit = {\nmethod = HttpMethod.parse(\"GET\")\nurl(ktorfitClient.baseUrl + \"/test\")\n}\nval _requestData = RequestData(returnTypeData = TypeData(\"kotlin.String\"),\nrequestTypeInfo = typeInfo<String>(),\nreturnTypeInfo = typeInfo<String>(),\nktorfitRequestBuilder = _ext)\n\nreturn ktorfitClient.suspendRequest<String, String>(_requestData)!!\n}\n}\n\npublic fun Ktorfit.createExampleApi(): ExampleApi = this.create(_ExampleApiImpl())\n
The next part is the compiler plugin which is added by the gradle plugin. It looks for the every usage of the create function from the Ktorfit-lib and adds an object of the wanted implementation class as an argument. Because of the naming convention of the generated classes we can deduce the name of the class from the name of type parameter.
val api = jvmKtorfit.create<ExampleApi>()\n
will be transformed to:
val api = jvmKtorfit.create<ExampleApi>(_ExampleApiImpl())\n
When the create() function is used, the object is cast to a KtorfitService and the client will be added. Then it is cast to requested type < T >
fun <T> create(ktorfitService: KtorfitService = DefaultKtorfitService()): T {\nif (ktorfitService is DefaultKtorfitService) {\nthrow IllegalArgumentException(\"You need to enable the Ktorfit Gradle Plugin\")\n}\nktorfitService.setClient(KtorfitClient(this))\nreturn ktorfitService as T\n}\n
By default, Ktorfit will throw compile error when it finds conditions under which it can\u2019t ensure that it will work correct. You can set an KSP argument to change this:
ksp {\narg(\"Ktorfit_Errors\", \"1\")\n}\n
You can set it in your build.gradle.kts file,
0: Turn off all Ktorfit related error checking
1: Check for errors
2: Turn errors into warnings
"},{"location":"configuration/#add-your-own-ktor-client","title":"Add your own Ktor client","text":"
You can set your Ktor client instance to the Ktorfit builder:
val myClient = HttpClient()\nval ktorfit = Ktorfit.Builder().httpClient(myClient).build()\n
plugins {\nid(\"com.google.devtools.ksp\") version \"CURRENT_KSP_VERSION\"\nid(\"de.jensklingenberg.ktorfit\") version \"1.7.0\"\n}\n
Next you have to add the Ktorfit KSP Plugin to the common target and every compilation target, where you want to use Ktorfit.
val ktorfitVersion = \"1.7.0\"\n\ndependencies {\nadd(\"kspCommonMainMetadata\", \"de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorfitVersion\")\nadd(\"ksp[NAMEOFPLATFORM]\",\"de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorfitVersion\")\n...\n}\n
[NAMEOFPLATFORM] is the name of the compilation target. When you want to use it for the Android module it\u2019s kspAndroid, for Js it\u2019s kspJs, etc. Look here for more information https://kotlinlang.org/docs/ksp-multiplatform.html
val ktorfitVersion = \"1.7.0\"\n\nsourceSets {\nval commonMain by getting{\ndependencies{\nimplementation(\"de.jensklingenberg.ktorfit:ktorfit-lib:$ktorfitVersion\")\n}\n}\n
Ktorfit is based on Ktor clients 2.3.4. You don\u2019t need to add an extra dependency for the default clients. When you want to use Ktor plugins for things like serialization, you need to add the dependencies, and they need to be compatible with 2.3.4
You can also use \u201cde.jensklingenberg.ktorfit:ktorfit-lib-light\u201d this will only add the Ktor client core dependency and not the platform dependencies for the clients. This will give you more control over the used clients, but you have to add them yourself. https://ktor.io/docs/http-client-engines.html Everything else is the same as \u201cktorfit-lib\u201d
Let\u2019s say you want to make a GET Request to https://swapi.dev/api/people/1/
Create a new Kotlin interface:
interface ExampleApi {\n@GET(\"people/1/\")\nsuspend fun getPerson(): String\n}\n
Now we add a function that will be used to make our request. The @GET annotation will tell Ktorfit that this a GET request. The value of @GET is the relative URL path that will be appended to the base url which we set later.
An interface used for Ktorfit needs to have a HTTP method annotation on every function. Because Ktor relies on Coroutines by default your functions need to have the suspend modifier. Alternatively you can use #Flow or Call
Info
The return type String will return the response text. When you want directly parse the response into a class you need to add a JSON,XML, etc. converter to Ktor
val ktorfit = Ktorfit.Builder().baseUrl(\"https://swapi.dev/api/\").build()\nval exampleApi = ktorfit.create<ExampleApi>()\n
Next we use the Ktorfit builder to create a Ktorfit instance, and set the base url . We can then use the create() function to receive an implementation of the wanted type.
val response = exampleApi.getPerson()\nprintln(response)\n
Ktorfit supports the following the HTTP method annotations:
@GET
@POST
@PUT
@DELETE
@HEAD
@OPTIONS
@PATCH
Or you can set your custom method to @HTTP
@GET(\"posts\")\nfun getPosts(): List<Post>\n
The value of the HTTP annotation will be appended to the baseUrl that you set in the Ktorfit builder. If the value contains a url that starts with http or https, this url will be used for the request instead of the baseUrl.
When you want to dynamically replace a part of the URL, you can use the @Path annotation.
interface ExampleApi {\n@GET(\"people/{peopleId}/\")\nsuspend fun getPerson(@Path(\"peopleId\") id: String): String\n}\n
Just write a part of your URL path in curly braces. Then you need to annotate a parameter with @Path. The value of @Path needs to match with one of the curly braces part in your URL path.
Example:
On a request with getPerson(1) , {peopleId} will be replaced with the argument 1 and the relative URL will become \u201cpeople/1/\u201d
interface ExampleService {\n@POST(\"upload\")\nsuspend fun upload(@Body map: MultiPartFormDataContent)\n}\n
To upload MultiPartFormData you need to have a parameter of the type MultiPartFormDataContent that is annotated with @Body. The method needs to be annotated with @POST or @PUT
@GET(\"comments\")\nsuspend fun getCommentsById(\n@Query(\"postId\") name: String,\n@ReqBuilder ext: HttpRequestBuilder.() -> Unit\n): List<Comment>\n
You need to set extra configuration on your request? Add a parameter with \u201c@ReqBuilder ext: HttpRequestBuilder.() -> Unit\u201d to your function.
val result = secondApi.getCommentsById(\"3\") {\nonDownload { bytesSentTotal, contentLength ->\nprintln(bytesSentTotal)\n}\n}\n
Then you can use the extension function to set additional configuration. The RequestBuilder will be applied last after everything that is set by Ktorfit
exampleApi.getPersonById(3).onExecute(object : Callback<People>{\noverride fun onResponse(call: People, response: HttpResponse) {\n//Do something with Response\n}\n\noverride fun onError(exception: Exception) {\n//Do something with exception\n}\n})\n
You can use Call to receive the response in a Callback."},{"location":"suspendresponseconverter/#your-own","title":"Your own","text":"
You can also add your own Converter. You just need to implement RequestConverter. Inside the converter you need to handle the conversion from suspend to your async code.
class MyOwnResponseConverter : SuspendResponseConverter {\n...\n
But you are only interested in the \u201cuser\u201d object, and you want to look your interface function something like this:
Example function
@GET(\"/user\")\nsuspend fun getUser(): User\n
First you need the Kotlin classes to which your JSON data is mapped to:
This example assumes that you are Kotlin Serialization
@kotlinx.serialization.Serializable\ndata class Envelope(val success: Boolean, val user: User)\n\n@kotlinx.serialization.Serializable\ndata class User(val id: Int, val name: String)\n
Now you need a converter that can convert the HTTPResponse and return a user object. Create a class that extends Converter.Factory
class UserFactory : Converter.Factory {\n\n}\n
Because in this case User is the return type of a suspend function, you need to create a SuspendResponseConverter. Override suspendResponseConverter()
class UserFactory : Converter.Factory {\noverride fun suspendResponseConverter(\ntypeData: TypeData,\nktorfit: Ktorfit\n): Converter.SuspendResponseConverter<HttpResponse, *>? {\n\n}\n}\n
Inside suspendResponseConverter you can decide if you want to return a converter. In our case we a converter for the type User. We can check that case with the typeData that we get as a parameter.
if (typeData.typeInfo.type == User::class) {\nreturn object : Converter.SuspendResponseConverter<HttpResponse, Any> {\noverride suspend fun convert(response: HttpResponse): Any {\n...\n}\n}\n}\n
Inside of convert we get the HttpResponse and we want to return a User object.
Now we could do the following:
When we know that this converter will always be used for a API that wraps the User inside an Envelope class, we can directly transform the body to an envelope object and just return the user object.
override suspend fun convert(response: HttpResponse): Any {\nval envelope = response.body<Envelope>()\nreturn envelope.user\n}\n
or we can create a TypeData of Envelope and use nextSuspendResponseConverter() to look up the next converter that can convert the response
override suspend fun convert(response: HttpResponse): Any {\nval typeData = TypeData.createTypeData(\"com.example.model.Envelope\", typeInfo<Envelope>())\nval envelope = ktorfit.nextSuspendResponseConverter(null, typeData)?.convert(response) as? Envelope\nreturn envelope.user\n}\n
Finally, add your converter factory to the Ktorfit Builder
@GET(\"posts/{postId}/comments\")\nsuspend fun getCommentsById(@RequestType(Int::class) @Path(\"postId\") postId: String): List<Comment>\n
You can set RequestType at a parameter with a type to which the parameter should be converted.
Then you need to implement a Converter factory with a RequestParameterConverter.
class StringToIntRequestConverterFactory : Converter.Factory {\noverride fun requestParameterConverter(\nparameterType: KClass<*>,\nrequestType: KClass<*>\n): Converter.RequestParameterConverter? {\nreturn object : Converter.RequestParameterConverter {\noverride fun convert(data: Any): Any {\n//convert the data\n}\n}\n}\n}\n
You only need ResponseConverters for cases where you can\u2019t use a suspend function in your interface. For every other case you want SuspendResponseConverter
Because Ktor relies on Coroutines by default your functions need to have the suspend modifier.
Let\u2019s say you have API endpoint to get a list of comments and you want to get them as Flow.
Ktorfit already has a converter for Flow, but it\u2019s used as an example
Now you need a converter that can convert the HTTPResponse and return a Flow. Create a class that extends Converter.Factory
class FlowConverterFactory : Converter.Factory {\n}\n
Next you need to overwrite responseConverter()
override fun responseConverter(\ntypeData: TypeData,\nktorfit: Ktorfit\n): Converter.ResponseConverter<HttpResponse, *>? {\n
Inside responseConverter you can decide if you want to return a converter. In our case we want a converter for the type Flow. We can check that case with the typeData that we get as a parameter.
Inside of convert we get the HttpResponse from getResponse(). We use nextSuspendResponseConverter to find the next converter that can convert the response. Then we put the converted response in the Flow and return it.
Finally, add your converter factory to the Ktorfit Builder
exampleApi.getPersonById(3).onExecute(object : Callback<People> {\noverride fun onResponse(call: People, response: HttpResponse) {\n//Do something with Response\n}\n\noverride fun onError(exception: Exception) {\n//Do something with exception\n}\n})\n
You can use Call to receive the response in a Callback."},{"location":"converters/suspendresponseconverter/","title":"SuspendResponseConverter","text":"
Let`s say you have a function that requests a list of comments
@GET(\"posts/{postId}/comments\")\nsuspend fun getCommentsByPostId(@Path(\"postId\") postId: Int): List<Comment>\n
But now you want to directly wrap your comment list in your data holder class e.g. \u201cMyOwnResponse\u201d
@GET(\"posts/{postId}/comments\")\nsuspend fun getCommentsByPostId(@Path(\"postId\") postId: Int): MyOwnResponse<List<Comment>>\n
"},{"location":"fundamentals/scope/","title":"Scope of Ktorfit","text":"
The goal of Ktorfit is to provide a similar developer experience like Retrofit for Kotlin Multiplatform projects. It`s not a 100% drop-in replacement for Retrofit. It uses Ktor clients because they are available on nearly every compile target of KMP. Every feature should be implemented so that it works on all platforms that Ktor supports. Before a new functionality is added to Ktorfit, it should be checked if there is already a Ktor plugin for it which solves the same problem.
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Overview","text":"Ktorfit"},{"location":"#introduction","title":"Introduction","text":"
Ktorfit is a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit
From now on with every Ktorfit release there will also be a Gradle plugin with the same version. That means that drop you can drop the Gradle extension block where you previously set the version number and just bump the number of the Gradle plugin. https://foso.github.io/Ktorfit/installation/
plugins {\nid(\"de.jensklingenberg.ktorfit\") version \"1.7.0\"\n}\n
"},{"location":"CHANGELOG/#143-2023-07-13","title":"1.4.3 - 2023-07-13","text":""},{"location":"CHANGELOG/#fixed_1","title":"Fixed","text":""},{"location":"CHANGELOG/#372-crash-with-xiaomi-on-create-ktorfitbuilder-by-princeparadoxes","title":"372 Crash with Xiaomi on create Ktorfit.Builder by @princeparadoxes","text":""},{"location":"CHANGELOG/#142-2023-06-25","title":"1.4.2 - 2023-06-25","text":""},{"location":"CHANGELOG/#fixed_2","title":"Fixed","text":""},{"location":"CHANGELOG/#323-code-generation-issue-for-multipart-formurlencoded-by-ph1ll1pp","title":"323 Code generation issue for @Multipart / @FormUrlEncoded by @Ph1ll1pp","text":""},{"location":"CHANGELOG/#141-2023-06-03","title":"1.4.1 - 2023-06-03","text":""},{"location":"CHANGELOG/#changed_5","title":"Changed","text":"
Upgrade dependencies: Ktor 2.3.1
"},{"location":"CHANGELOG/#fixed_3","title":"Fixed","text":""},{"location":"CHANGELOG/#236-parsing-error-for-listarray","title":"236 Parsing error for list/array","text":""},{"location":"CHANGELOG/#140-2023-05-27","title":"1.4.0 - 2023-05-27","text":""},{"location":"CHANGELOG/#added_2","title":"Added","text":"
e.g.
interface ExampleApi{\nsuspend fun getUser(): Response<User>\n}\n\nval user = userKtorfit.create<ExampleApi>().getUser()\n\nif(user.isSuccessful){\nuser.body()\n}else{\nuser.errorBody()\n}\n
Ktorfit is now using converters factories to apply the converters, similar to Retrofit see more here https://foso.github.io/Ktorfit/converters/converters/
TypeData now has a field \u201ctypeInfo\u201d can be used to convert the Ktor HttpResponse body to the wanted type
CallConverterFactory for replacement of CallResponseConverter
FlowConverterFactory for replacement of FlowResponseConverter
Added support for targets: macosArm64, tvosArm64, tvosX64, tvosSimulatorArm64, watchosSimulatorArm64 #315
"},{"location":"CHANGELOG/#85-added-a-response-class-that-can-be-used-as-a-wrapper-around-the-api-response-the-converter-for-it-is-automatically-applied-thx-to-vovahost-datl4g","title":"85 Added a Response class that can be used as a wrapper around the API Response, the converter for it is automatically applied. thx to @vovahost, @DATL4G","text":""},{"location":"CHANGELOG/#changed_6","title":"Changed","text":"
Optimized generated code, the generated code that is used for a request will now directly set the Ktor code instead of delegating it to a Ktorfit class. This will make the code easier to understand.
From now on there are two versions of the ktorfit-lib.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib\u201d will stay like before and add the platform client dependencies for the clients.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib-light\u201d this will only add the client core dependency and not the platform dependencies for the clients. This will give you more control over the used clients, but you have to add them yourself. https://ktor.io/docs/http-client-engines.html Everything else is the same as \u201cktorfit-lib\u201d
From now on there are two versions of the ktorfit-lib.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib\u201d will stay like before and add the platform client dependencies for the clients.
\u201cde.jensklingenberg.ktorfit:ktorfit-lib-light\u201d this will only add the client core dependency and not the platform dependencies for the clients. This will give you more control over the used clients, but you have to add them yourself. https://ktor.io/docs/http-client-engines.html Everything else is the same as \u201cktorfit-lib\u201d
kotlinx.coroutines.JobCancellationException: Parent job is Completed #70
\ud83d\udca5 Breaking changes
reverted the api of converters to the state of beta13, see #71
when you are updating from beta13, this is the only change to converters: returnTypeName is replaced through typeData, you can use typeData.qualifiedName to get the same value as returnTypeName
NEW: - Query parameters can now be nullable, null values will be ignored in requests - Function return types can now be nullable
FIX: - Url annotation not resolved correctly #65
BREAKING CHANGES: - Changed naming of Converters:
SuspendResponseConverter:
is now called RequestConverter
the wrapSuspendResponse is now called convertRequest.
returnTypeName is replaced through typeData, you can use typeData.qualifiedName to get the same value as returnTypeName RequestConverter need to be added with the requestConverter() on your Ktorfit object.
https://foso.github.io/Ktorfit/requestconverter/
ResponseConverters:
returnTypeName is replaced through typeData, you can use typeData.qualifiedName to get the same value as returnTypeName https://foso.github.io/Ktorfit/responseconverter/
wrapResponse from SuspendResponseConverter got renamed to wrapSuspendResponse. This add the possibility to have ResponseConverter and SuspendResponseConverter implemented in the same class.
throw compiler time error when you use @Path without the corresponding value inside the relative url path
every generated implementation class of an interface that Ktorfit generates will now contain a \u201ccreate\u201d ext function that can be used instead of the generic create() function e.g. Let\u2019s say you have a interface GithubService, then you can create an instance like this:
val ktorfit = ktorfit {\nbaseUrl(\"http://example.com/\")\n}.create<GithubService>()\n
or this
val ktorfit = ktorfit {\nbaseUrl(\"http://example.com/\")\n}.createGithubService()\n
By default, IntelliJ/Android Studio can\u2019t find the generated code, you need to add the KSP generated folder to the sourcesets like this: (See more here: https://kotlinlang.org/docs/ksp-quickstart.html#make-ide-aware-of-generated-code)
Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Definitions.
\u201cLicense\u201d shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
\u201cLicensor\u201d shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
\u201cLegal Entity\u201d shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \u201ccontrol\u201d means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
\u201cYou\u201d (or \u201cYour\u201d) shall mean an individual or Legal Entity exercising permissions granted by this License.
\u201cSource\u201d form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
\u201cObject\u201d form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
\u201cWork\u201d shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
\u201cDerivative Works\u201d shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
\u201cContribution\u201d shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \u201csubmitted\u201d means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \u201cNot a Contribution.\u201d
\u201cContributor\u201d shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
\u00a9 You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a \u201cNOTICE\u201d text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n
Copyright 2022 Jens Klingenberg
Licensed under the Apache License, Version 2.0 (the \u201cLicense\u201d); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0\n
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
"},{"location":"architecture/","title":"How Ktorfit works under the hood","text":"
Ktorfit consists of three main components KSP-Plugin, Compiler plugin and the Ktorfit lib
package com.example\n\nimport com.example.model.People\nimport de.jensklingenberg.ktorfit.http.GET\n\ninterface ExampleApi {\n@GET(\"/test\")\nsuspend fun exampleGet(): People\n}\n
Let`s say we have a interface like this.
At compile time Ktorfit/KSP checks for all functions that are annotated with Ktorfit annotations like @GET.
Then it looks at the parent interfaces of that functions and generates, the source code of a Kotlin class that implements the interface. The classes are named like the interfaces but with an underscore at the beginning and \u201cImpl\u201d at the end, and they have the same package as the interfaces. In this case a class named _ExampleApiImpl will be generated. The class will also implement KtorfitService. The setClient() function will be used to add the http client at runtime.
@OptIn(InternalKtorfitApi::class)\npublic class _ExampleApiImpl : ExampleApi, KtorfitService {\npublic override lateinit var ktorfitClient: Client\n\npublic override suspend fun exampleGet(): String {\nval _ext: HttpRequestBuilder.() -> Unit = {\nmethod = HttpMethod.parse(\"GET\")\nurl(ktorfitClient.baseUrl + \"/test\")\n}\nval _requestData = RequestData(returnTypeData = TypeData(\"kotlin.String\"),\nrequestTypeInfo = typeInfo<String>(),\nreturnTypeInfo = typeInfo<String>(),\nktorfitRequestBuilder = _ext)\n\nreturn ktorfitClient.suspendRequest<String, String>(_requestData)!!\n}\n}\n\npublic fun Ktorfit.createExampleApi(): ExampleApi = this.create(_ExampleApiImpl())\n
The next part is the compiler plugin which is added by the gradle plugin. It looks for the every usage of the create function from the Ktorfit-lib and adds an object of the wanted implementation class as an argument. Because of the naming convention of the generated classes we can deduce the name of the class from the name of type parameter.
val api = jvmKtorfit.create<ExampleApi>()\n
will be transformed to:
val api = jvmKtorfit.create<ExampleApi>(_ExampleApiImpl())\n
When the create() function is used, the object is cast to a KtorfitService and the client will be added. Then it is cast to requested type < T >
fun <T> create(ktorfitService: KtorfitService = DefaultKtorfitService()): T {\nif (ktorfitService is DefaultKtorfitService) {\nthrow IllegalArgumentException(\"You need to enable the Ktorfit Gradle Plugin\")\n}\nktorfitService.setClient(KtorfitClient(this))\nreturn ktorfitService as T\n}\n
By default, Ktorfit will throw compile error when it finds conditions under which it can\u2019t ensure that it will work correct. You can set an KSP argument to change this:
ksp {\narg(\"Ktorfit_Errors\", \"1\")\n}\n
You can set it in your build.gradle.kts file,
0: Turn off all Ktorfit related error checking
1: Check for errors
2: Turn errors into warnings
"},{"location":"configuration/#add-your-own-ktor-client","title":"Add your own Ktor client","text":"
You can set your Ktor client instance to the Ktorfit builder:
val myClient = HttpClient()\nval ktorfit = Ktorfit.Builder().httpClient(myClient).build()\n
plugins {\nid(\"com.google.devtools.ksp\") version \"CURRENT_KSP_VERSION\"\nid(\"de.jensklingenberg.ktorfit\") version \"1.7.0\"\n}\n
Next you have to add the Ktorfit KSP Plugin to the common target and every compilation target, where you want to use Ktorfit.
val ktorfitVersion = \"1.7.0\"\n\ndependencies {\nadd(\"kspCommonMainMetadata\", \"de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorfitVersion\")\nadd(\"ksp[NAMEOFPLATFORM]\",\"de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorfitVersion\")\n...\n}\n
[NAMEOFPLATFORM] is the name of the compilation target. When you want to use it for the Android module it\u2019s kspAndroid, for Js it\u2019s kspJs, etc. Look here for more information https://kotlinlang.org/docs/ksp-multiplatform.html
val ktorfitVersion = \"1.7.0\"\n\nsourceSets {\nval commonMain by getting{\ndependencies{\nimplementation(\"de.jensklingenberg.ktorfit:ktorfit-lib:$ktorfitVersion\")\n}\n}\n
Ktorfit is based on Ktor clients 2.3.4. You don\u2019t need to add an extra dependency for the default clients. When you want to use Ktor plugins for things like serialization, you need to add the dependencies, and they need to be compatible with 2.3.4
You can also use \u201cde.jensklingenberg.ktorfit:ktorfit-lib-light\u201d this will only add the Ktor client core dependency and not the platform dependencies for the clients. This will give you more control over the used clients, but you have to add them yourself. https://ktor.io/docs/http-client-engines.html Everything else is the same as \u201cktorfit-lib\u201d
Let\u2019s say you want to make a GET Request to https://swapi.dev/api/people/1/
Create a new Kotlin interface:
interface ExampleApi {\n@GET(\"people/1/\")\nsuspend fun getPerson(): String\n}\n
Now we add a function that will be used to make our request. The @GET annotation will tell Ktorfit that this a GET request. The value of @GET is the relative URL path that will be appended to the base url which we set later.
An interface used for Ktorfit needs to have a HTTP method annotation on every function. Because Ktor relies on Coroutines by default your functions need to have the suspend modifier. Alternatively you can use #Flow or Call
Info
The return type String will return the response text. When you want directly parse the response into a class you need to add a JSON,XML, etc. converter to Ktor
val ktorfit = Ktorfit.Builder().baseUrl(\"https://swapi.dev/api/\").build()\nval exampleApi = ktorfit.create<ExampleApi>()\n
Next we use the Ktorfit builder to create a Ktorfit instance, and set the base url . We can then use the create() function to receive an implementation of the wanted type.
val response = exampleApi.getPerson()\nprintln(response)\n
Ktorfit supports the following the HTTP method annotations:
@GET
@POST
@PUT
@DELETE
@HEAD
@OPTIONS
@PATCH
Or you can set your custom method to @HTTP
@GET(\"posts\")\nfun getPosts(): List<Post>\n
The value of the HTTP annotation will be appended to the baseUrl that you set in the Ktorfit builder. If the value contains a url that starts with http or https, this url will be used for the request instead of the baseUrl.
When you want to dynamically replace a part of the URL, you can use the @Path annotation.
interface ExampleApi {\n@GET(\"people/{peopleId}/\")\nsuspend fun getPerson(@Path(\"peopleId\") id: String): String\n}\n
Just write a part of your URL path in curly braces. Then you need to annotate a parameter with @Path. The value of @Path needs to match with one of the curly braces part in your URL path.
Example:
On a request with getPerson(1) , {peopleId} will be replaced with the argument 1 and the relative URL will become \u201cpeople/1/\u201d
interface ExampleService {\n@POST(\"upload\")\nsuspend fun upload(@Body map: MultiPartFormDataContent)\n}\n
To upload MultiPartFormData you need to have a parameter of the type MultiPartFormDataContent that is annotated with @Body. The method needs to be annotated with @POST or @PUT
@GET(\"comments\")\nsuspend fun getCommentsById(\n@Query(\"postId\") name: String,\n@ReqBuilder ext: HttpRequestBuilder.() -> Unit\n): List<Comment>\n
You need to set extra configuration on your request? Add a parameter with \u201c@ReqBuilder ext: HttpRequestBuilder.() -> Unit\u201d to your function.
val result = secondApi.getCommentsById(\"3\") {\nonDownload { bytesSentTotal, contentLength ->\nprintln(bytesSentTotal)\n}\n}\n
Then you can use the extension function to set additional configuration. The RequestBuilder will be applied last after everything that is set by Ktorfit
exampleApi.getPersonById(3).onExecute(object : Callback<People>{\noverride fun onResponse(call: People, response: HttpResponse) {\n//Do something with Response\n}\n\noverride fun onError(exception: Exception) {\n//Do something with exception\n}\n})\n
You can use Call to receive the response in a Callback."},{"location":"suspendresponseconverter/#your-own","title":"Your own","text":"
You can also add your own Converter. You just need to implement RequestConverter. Inside the converter you need to handle the conversion from suspend to your async code.
class MyOwnResponseConverter : SuspendResponseConverter {\n...\n
But you are only interested in the \u201cuser\u201d object, and you want to look your interface function something like this:
Example function
@GET(\"/user\")\nsuspend fun getUser(): User\n
First you need the Kotlin classes to which your JSON data is mapped to:
This example assumes that you are Kotlin Serialization
@kotlinx.serialization.Serializable\ndata class Envelope(val success: Boolean, val user: User)\n\n@kotlinx.serialization.Serializable\ndata class User(val id: Int, val name: String)\n
Now you need a converter that can convert the HTTPResponse and return a user object. Create a class that extends Converter.Factory
class UserFactory : Converter.Factory {\n\n}\n
Because in this case User is the return type of a suspend function, you need to create a SuspendResponseConverter. Override suspendResponseConverter()
class UserFactory : Converter.Factory {\noverride fun suspendResponseConverter(\ntypeData: TypeData,\nktorfit: Ktorfit\n): Converter.SuspendResponseConverter<HttpResponse, *>? {\n\n}\n}\n
Inside suspendResponseConverter you can decide if you want to return a converter. In our case we a converter for the type User. We can check that case with the typeData that we get as a parameter.
if (typeData.typeInfo.type == User::class) {\nreturn object : Converter.SuspendResponseConverter<HttpResponse, Any> {\noverride suspend fun convert(response: HttpResponse): Any {\n...\n}\n}\n}\n
Inside of convert we get the HttpResponse and we want to return a User object.
Now we could do the following:
When we know that this converter will always be used for a API that wraps the User inside an Envelope class, we can directly transform the body to an envelope object and just return the user object.
override suspend fun convert(response: HttpResponse): Any {\nval envelope = response.body<Envelope>()\nreturn envelope.user\n}\n
or we can create a TypeData of Envelope and use nextSuspendResponseConverter() to look up the next converter that can convert the response
override suspend fun convert(response: HttpResponse): Any {\nval typeData = TypeData.createTypeData(\"com.example.model.Envelope\", typeInfo<Envelope>())\nval envelope = ktorfit.nextSuspendResponseConverter(null, typeData)?.convert(response) as? Envelope\nreturn envelope.user\n}\n
Finally, add your converter factory to the Ktorfit Builder
@GET(\"posts/{postId}/comments\")\nsuspend fun getCommentsById(@RequestType(Int::class) @Path(\"postId\") postId: String): List<Comment>\n
You can set RequestType at a parameter with a type to which the parameter should be converted.
Then you need to implement a Converter factory with a RequestParameterConverter.
class StringToIntRequestConverterFactory : Converter.Factory {\noverride fun requestParameterConverter(\nparameterType: KClass<*>,\nrequestType: KClass<*>\n): Converter.RequestParameterConverter? {\nreturn object : Converter.RequestParameterConverter {\noverride fun convert(data: Any): Any {\n//convert the data\n}\n}\n}\n}\n
You only need ResponseConverters for cases where you can\u2019t use a suspend function in your interface. For every other case you want SuspendResponseConverter
Because Ktor relies on Coroutines by default your functions need to have the suspend modifier.
Let\u2019s say you have API endpoint to get a list of comments and you want to get them as Flow.
Ktorfit already has a converter for Flow, but it\u2019s used as an example
Now you need a converter that can convert the HTTPResponse and return a Flow. Create a class that extends Converter.Factory
class FlowConverterFactory : Converter.Factory {\n}\n
Next you need to overwrite responseConverter()
override fun responseConverter(\ntypeData: TypeData,\nktorfit: Ktorfit\n): Converter.ResponseConverter<HttpResponse, *>? {\n
Inside responseConverter you can decide if you want to return a converter. In our case we want a converter for the type Flow. We can check that case with the typeData that we get as a parameter.
Inside of convert we get the HttpResponse from getResponse(). We use nextSuspendResponseConverter to find the next converter that can convert the response. Then we put the converted response in the Flow and return it.
Finally, add your converter factory to the Ktorfit Builder
exampleApi.getPersonById(3).onExecute(object : Callback<People> {\noverride fun onResponse(call: People, response: HttpResponse) {\n//Do something with Response\n}\n\noverride fun onError(exception: Exception) {\n//Do something with exception\n}\n})\n
You can use Call to receive the response in a Callback."},{"location":"converters/suspendresponseconverter/","title":"SuspendResponseConverter","text":"
Let`s say you have a function that requests a list of comments
@GET(\"posts/{postId}/comments\")\nsuspend fun getCommentsByPostId(@Path(\"postId\") postId: Int): List<Comment>\n
But now you want to directly wrap your comment list in your data holder class e.g. \u201cMyOwnResponse\u201d
@GET(\"posts/{postId}/comments\")\nsuspend fun getCommentsByPostId(@Path(\"postId\") postId: Int): MyOwnResponse<List<Comment>>\n
"},{"location":"fundamentals/scope/","title":"Scope of Ktorfit","text":"
The goal of Ktorfit is to provide a similar developer experience like Retrofit for Kotlin Multiplatform projects. It`s not a 100% drop-in replacement for Retrofit. It uses Ktor clients because they are available on nearly every compile target of KMP. Every feature should be implemented so that it works on all platforms that Ktor supports. Before a new functionality is added to Ktorfit, it should be checked if there is already a Ktor plugin for it which solves the same problem.