diff --git a/404.html b/404.html
index 929c035b2..f323cd3ff 100644
--- a/404.html
+++ b/404.html
@@ -18,4 +18,4 @@
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
--->
All important changes of this project must be documented in this file.
The format is based on Keep a Changelog and this project orients towards Semantic Versioning. Note: This project needs KSP to work and every new Ktorfit with an update of the KSP version is technically a breaking change. But there is no intent to bump the Ktorfit major version for every KSP update.
The needed dependencies for Ktorfit KSP processor are now included in the Ktorfit Gradle plugin. You can remove the ksp() block from your build.gradle.kts file. You still need to apply the KSP plugin.
All important changes of this project must be documented in this file.
The format is based on Keep a Changelog and this project orients towards Semantic Versioning. Note: This project needs KSP to work and every new Ktorfit with an update of the KSP version is technically a breaking change. But there is no intent to bump the Ktorfit major version for every KSP update.
By default, nullable response types will not throw an exception. You can now override this behavior by adding the DontSwallowExceptionsConverterFactory or your own ConverterFactory to the converterFactories. #618
The needed dependencies for Ktorfit KSP processor are now included in the Ktorfit Gradle plugin. You can remove the ksp() block from your build.gradle.kts file. You still need to apply the KSP plugin.
However, if you want to keep the old behavior and generate qualifiedTypename, you can set it in the Ktorfit config generateQualifiedTypeName to true in your build.gradle.kts file.
build.gradle.kts
ktorfit{generateQualifiedTypeName=true}
-
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
The deprecated code got removed. This will simplify the codebase and make it easier to maintain. When you haven’t used the deprecated converters, there is not much you need to change. Some converters that were previously auto applied now need to be added manually. See the migration guide for more information: https://foso.github.io/Ktorfit/migration/#from-2-to-200
In the previous versions of Ktorfit, the qualifiedTypename was always generated in the code. This was used in the TypeData.createTypeData() function to provide a fully qualified type name for the data type being used.
val_typeData=TypeData.createTypeData(
+
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
The deprecated code got removed. This will simplify the codebase and make it easier to maintain. When you haven’t used the deprecated converters, there is not much you need to change. Some converters that were previously auto applied now need to be added manually. See the migration guide for more information: https://foso.github.io/Ktorfit/migration/#from-2-to-200
In the previous versions of Ktorfit, the qualifiedTypename was always generated in the code. This was used in the TypeData.createTypeData() function to provide a fully qualified type name for the data type being used.
However, if you want to keep the old behavior and generate qualifiedTypename, you can set a KSP argument Ktorfit_QualifiedTypeName to true in your build.gradle.kts file.
ksp{arg("Ktorfit_QualifiedTypeName","true")}
-
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
! When you still use the deprecated converters because there are use cases which you can’t do with the converter factories, please write a GitHub Issue. The deprecated converters will be removed in one of the upcoming versions
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{
+
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
! When you still use the deprecated converters because there are use cases which you can’t do with the converter factories, please write a GitHub Issue. The deprecated converters will be removed in one of the upcoming versions
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/
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¶
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¶
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.
“de.jensklingenberg.ktorfit:ktorfit-lib” will stay like before and add the platform client dependencies for the clients.
“de.jensklingenberg.ktorfit:ktorfit-lib-light” 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 “ktorfit-lib”
From now on there are two versions of the ktorfit-lib.
“de.jensklingenberg.ktorfit:ktorfit-lib” will stay like before and add the platform client dependencies for the clients.
“de.jensklingenberg.ktorfit:ktorfit-lib-light” 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 “ktorfit-lib”
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.
“de.jensklingenberg.ktorfit:ktorfit-lib” will stay like before and add the platform client dependencies for the clients.
“de.jensklingenberg.ktorfit:ktorfit-lib-light” 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 “ktorfit-lib”
From now on there are two versions of the ktorfit-lib.
“de.jensklingenberg.ktorfit:ktorfit-lib” will stay like before and add the platform client dependencies for the clients.
“de.jensklingenberg.ktorfit:ktorfit-lib-light” 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 “ktorfit-lib”
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Definitions.
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
“Legal Entity” 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, “control” 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.
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
“Object” 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.
“Work” 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).
“Derivative Works” 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.
“Contribution” 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, “submitted” 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 “Not a Contribution.”
“Contributor” 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
(d) If the Work includes a “NOTICE” 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 “AS IS” 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
@@ -10,4 +10,4 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2022 Jens Klingenberg
Licensed under the Apache License, Version 2.0 (the “License”); 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
-
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” 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.
Last update: March 3, 2023
\ No newline at end of file
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” 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.
Last update: March 3, 2023
\ No newline at end of file
diff --git a/android/proguard/index.html b/android/proguard/index.html
index a8dce6493..64a94d146 100644
--- a/android/proguard/index.html
+++ b/android/proguard/index.html
@@ -1,3 +1,3 @@
- proguard - Ktorfit
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.
By default, Ktorfit will throw compile error when it finds conditions under which it can’t ensure that it will work correct. You can set it in the Ktorfit config to change this
By default, Ktorfit will throw compile error when it finds conditions under which it can’t ensure that it will work correct. You can set it in the Ktorfit config to change this
You only need ResponseConverters for cases where you can’t 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’s 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’s used as an example
You only need ResponseConverters for cases where you can’t 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’s 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’s used as an example
@GET("/user")fungetUser():Flow<List<Commment>>
Now you need a converter that can convert the HTTPResponse and return a Flow. Create a class that extends Converter.Factory
classFlowConverterFactory:Converter.Factory{}
@@ -55,4 +55,4 @@
//Do something with exception}})
-
You can use Call to receive the response in a Callback.
Last update: May 26, 2024
\ No newline at end of file
+
You can use Call to receive the response in a Callback.
Last update: May 26, 2024
\ No newline at end of file
diff --git a/converters/suspendresponseconverter/index.html b/converters/suspendresponseconverter/index.html
index a346d7a6d..d236c053f 100644
--- a/converters/suspendresponseconverter/index.html
+++ b/converters/suspendresponseconverter/index.html
@@ -1,4 +1,4 @@
- SuspendResponseConverter - Ktorfit
\ No newline at end of file
diff --git a/development/index.html b/development/index.html
index fc0da2324..7be69c4c5 100644
--- a/development/index.html
+++ b/development/index.html
@@ -1 +1 @@
- Development - Ktorfit
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.
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.
Last update: March 4, 2023
\ No newline at end of file
diff --git a/index.html b/index.html
index 958cf45dd..0bfea7db6 100644
--- a/index.html
+++ b/index.html
@@ -1 +1 @@
- Ktorfit
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
You can also use “de.jensklingenberg.ktorfit:ktorfit-lib-light” 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 “ktorfit-lib”
Ktorfit is based on Ktor clients 2.3.11. You don’t 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.11
Last update: May 26, 2024
\ No newline at end of file
+
You can also use “de.jensklingenberg.ktorfit:ktorfit-lib-light” 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 “ktorfit-lib”
Ktorfit is based on Ktor clients 2.3.12. You don’t 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.12
Last update: May 26, 2024
\ No newline at end of file
diff --git a/knownissues/index.html b/knownissues/index.html
new file mode 100644
index 000000000..938bdfe79
--- /dev/null
+++ b/knownissues/index.html
@@ -0,0 +1 @@
+ Known issues - Ktorfit
When you have a KMP project with a single target, IntelliJ will find the generated “create” extension function (e.g. ktorfit.createExampleApi()) in your common module, but the compilation will fail because of an “Unresolved reference” error. In that case, you have to use ktorfit.create<ExampleApi>() to make it work, even though it’s already deprecated.
Kotlin handles the compilation of a KMP project with a single target differently than with multiple targets.
Next we use the Ktorfit builder to create a Ktorfit instance, and set the base url. After compiling the project we can then use the generated extension function to receive an implementation of the wanted type.
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")fungetPosts():List<Post>
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.
Then you can use the extension function to set additional configuration. The RequestBuilder will be applied last after everything that is set by Ktorfit
Last update: October 21, 2023
\ No newline at end of file
+
Then you can use the extension function to set additional configuration. The RequestBuilder will be applied last after everything that is set by Ktorfit
Last update: October 21, 2023
\ No newline at end of file
diff --git a/responseconverter/index.html b/responseconverter/index.html
index 0d4712923..bc1b1fbf3 100644
--- a/responseconverter/index.html
+++ b/responseconverter/index.html
@@ -1,4 +1,4 @@
- Responseconverter - Ktorfit
\ No newline at end of file
diff --git a/search/search_index.json b/search/search_index.json
index 7e0de7900..64a153e9d 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
All important changes of this project must be documented in this file.
The format is based on Keep a Changelog and this project orients towards Semantic Versioning. Note: This project needs KSP to work and every new Ktorfit with an update of the KSP version is technically a breaking change. But there is no intent to bump the Ktorfit major version for every KSP update.
The needed dependencies for Ktorfit KSP processor are now included in the Ktorfit Gradle plugin. You can remove the ksp() block from your build.gradle.kts file. You still need to apply the KSP plugin.
plugins {\nid(\"com.google.devtools.ksp\") version \"CURRENT_KSP_VERSION\"\nid(\"de.jensklingenberg.ktorfit\") version \"2.0.0\"\n}\n
See the installation guide for more information: https://foso.github.io/Ktorfit/installation/
The code that is generated by KSP is now accessible from the module where the interface is defined. That means code from commonMain can now find the generated code. Generated code from the platform specific code is still only available from the specific modules.
The create function is now deprecated. The reason for that is that it is relying on a compiler plugin to work. This can lead to compile errors when the class can\u2019t be found. The plan is to get rid of the plugin. When your project is configured correct, the autocompletion should show an extension function create followed by the name of the interface. This function will not trigger the compiler plugin
The deprecated code got removed. This will simplify the codebase and make it easier to maintain. When you haven\u2019t used the deprecated converters, there is not much you need to change. The dependencies for the converters that were previously auto added now need to be added manually. See the migration guide for more information: https://foso.github.io/Ktorfit/migration/#from-2-to-200
QualifiedTypeName in Ktorfit
In the previous versions of Ktorfit, the qualifiedTypename was always generated in the code. This was used in the TypeData.createTypeData() function to provide a fully qualified type name for the data type being used.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\nqualifiedTypename = \"de.jensklingenberg.ktorfit.Call<com.example.model.People>\"\n)\n
In the new version of Ktorfit, this behavior has been changed. Now, by default, Ktorfit will keep qualifiedTypename for TypeData in the generated code empty. This means that the qualifiedTypename will not be automatically generated.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\n)\n
However, if you want to keep the old behavior and generate qualifiedTypename, you can set it in the Ktorfit config generateQualifiedTypeName to true in your build.gradle.kts file.
build.gradle.kts
ktorfit {\ngenerateQualifiedTypeName = true\n}\n
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
The deprecated code got removed. This will simplify the codebase and make it easier to maintain. When you haven\u2019t used the deprecated converters, there is not much you need to change. Some converters that were previously auto applied now need to be added manually. See the migration guide for more information: https://foso.github.io/Ktorfit/migration/#from-2-to-200
"},{"location":"CHANGELOG/#qualifiedtypename-in-ktorfit","title":"QualifiedTypeName in Ktorfit","text":"
In the previous versions of Ktorfit, the qualifiedTypename was always generated in the code. This was used in the TypeData.createTypeData() function to provide a fully qualified type name for the data type being used.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\nqualifiedTypename = \"de.jensklingenberg.ktorfit.Call<com.example.model.People>\"\n)\n
In the new version of Ktorfit, this behavior has been changed. Now, by default, Ktorfit will keep qualifiedTypename for TypeData in the generated code empty. This means that the qualifiedTypename will not be automatically generated.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\n)\n
However, if you want to keep the old behavior and generate qualifiedTypename, you can set a KSP argument Ktorfit_QualifiedTypeName to true in your build.gradle.kts file.
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
Deprecated the convert function in the SuspendResponseConverter interface See: https://foso.github.io/Ktorfit/migration/#from-170-to-181
! When you still use the deprecated converters because there are use cases which you can\u2019t do with the converter factories, please write a GitHub Issue. The deprecated converters will be removed in one of the upcoming versions
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_5","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_6","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_9","title":"Changed","text":"
Upgrade dependencies: Ktor 2.3.1
"},{"location":"CHANGELOG/#fixed_7","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_4","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_10","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.
@OptIn(InternalKtorfitApi::class)\npublic class _ExampleApiImpl(\nprivate val _ktorfit: Ktorfit,\n) : ExampleApi {\npublic val _converter: KtorfitConverterHelper = KtorfitConverterHelper(_ktorfit)\n\noverride suspend fun exampleGet(): People {\nval _ext: HttpRequestBuilder.() -> Unit = {\nmethod = HttpMethod.parse(\"GET\")\nurl{\ntakeFrom(_ktorfit.baseUrl + \"/test\")\n}\n}\nval _typeData = TypeData.createTypeData(qualifiedTypename = \"com.example.model.People\",\ntypeInfo = typeInfo<People>())\n\nreturn _converter.suspendRequest<People, People>(_typeData,_ext)!!\n}\n}\n\npublic fun Ktorfit.createExampleApi(): ExampleApi = this.create(_ExampleApiImpl(this))\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(jvmKtorfit))\n
The create() function is used, checks that the compiler plugin replaced the default value
public fun <T> create(data: T? = null): T {\nif (data == null) {\nthrow IllegalArgumentException(ENABLE_GRADLE_PLUGIN)\n}\nreturn data\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 it in the Ktorfit config to change this
"},{"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
"},{"location":"development/","title":"Development","text":""},{"location":"development/#update-ktorfit-for-new-kotlin-version","title":"Update Ktorfit for new Kotlin version","text":"
Bump kotlin in libs.versions
Change ktorfitCompiler in libs.versions to KTORFIT_VERSION-NEW_KOTLIN_VERSION
Add the Ktorfit-lib to your common module. You can find all available versions here
val ktorfitVersion = \"2.0.1\"\n\nsourceSets {\nval commonMain by getting{\ndependencies{\nimplementation(\"de.jensklingenberg.ktorfit:ktorfit-lib:$ktorfitVersion\")\n}\n}\n
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
Ktorfit is based on Ktor clients 2.3.11. 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.11
"},{"location":"migration/#from-170-to-181","title":"From 1.7.0 to 1.8.1","text":""},{"location":"migration/#suspendresponseconverter","title":"SuspendResponseConverter","text":"
Implement override suspend fun convert(result: KtorfitResult)
public suspend fun convert(result: KtorfitResult): T {\nreturn when (result) {\nis KtorfitResult.Failure -> {\nthrow result.throwable // Or do something with the throwable\n}\n\nis KtorfitResult.Success -> {\nval response = result.response\n//Put the code that was in your other convert function here\n}\n}\n}\n
Redirect the deprecated function to the new function:
override suspend fun convert(response: HttpResponse): Any {\nreturn convert(KtorfitResult.Success(response))\n}\n
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.createExampleApi()\n
Next we use the Ktorfit builder to create a Ktorfit instance, and set the base url. After compiling the project we can then use the generated extension 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
All important changes of this project must be documented in this file.
The format is based on Keep a Changelog and this project orients towards Semantic Versioning. Note: This project needs KSP to work and every new Ktorfit with an update of the KSP version is technically a breaking change. But there is no intent to bump the Ktorfit major version for every KSP update.
By default, nullable response types will not throw an exception. You can now override this behavior by adding the DontSwallowExceptionsConverterFactory or your own ConverterFactory to the converterFactories. #618
The needed dependencies for Ktorfit KSP processor are now included in the Ktorfit Gradle plugin. You can remove the ksp() block from your build.gradle.kts file. You still need to apply the KSP plugin.
plugins {\nid(\"com.google.devtools.ksp\") version \"CURRENT_KSP_VERSION\"\nid(\"de.jensklingenberg.ktorfit\") version \"2.0.0\"\n}\n
See the installation guide for more information: https://foso.github.io/Ktorfit/installation/
The code that is generated by KSP is now accessible from the module where the interface is defined. That means code from commonMain can now find the generated code. Generated code from the platform specific code is still only available from the specific modules.
The create function is now deprecated. The reason for that is that it is relying on a compiler plugin to work. This can lead to compile errors when the class can\u2019t be found. The plan is to get rid of the plugin. When your project is configured correct, the autocompletion should show an extension function create followed by the name of the interface. This function will not trigger the compiler plugin
The deprecated code got removed. This will simplify the codebase and make it easier to maintain. When you haven\u2019t used the deprecated converters, there is not much you need to change. The dependencies for the converters that were previously auto added now need to be added manually. See the migration guide for more information: https://foso.github.io/Ktorfit/migration/#from-2-to-200
QualifiedTypeName in Ktorfit
In the previous versions of Ktorfit, the qualifiedTypename was always generated in the code. This was used in the TypeData.createTypeData() function to provide a fully qualified type name for the data type being used.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\nqualifiedTypename = \"de.jensklingenberg.ktorfit.Call<com.example.model.People>\"\n)\n
In the new version of Ktorfit, this behavior has been changed. Now, by default, Ktorfit will keep qualifiedTypename for TypeData in the generated code empty. This means that the qualifiedTypename will not be automatically generated.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\n)\n
However, if you want to keep the old behavior and generate qualifiedTypename, you can set it in the Ktorfit config generateQualifiedTypeName to true in your build.gradle.kts file.
build.gradle.kts
ktorfit {\ngenerateQualifiedTypeName = true\n}\n
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
The deprecated code got removed. This will simplify the codebase and make it easier to maintain. When you haven\u2019t used the deprecated converters, there is not much you need to change. Some converters that were previously auto applied now need to be added manually. See the migration guide for more information: https://foso.github.io/Ktorfit/migration/#from-2-to-200
"},{"location":"CHANGELOG/#qualifiedtypename-in-ktorfit","title":"QualifiedTypeName in Ktorfit","text":"
In the previous versions of Ktorfit, the qualifiedTypename was always generated in the code. This was used in the TypeData.createTypeData() function to provide a fully qualified type name for the data type being used.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\nqualifiedTypename = \"de.jensklingenberg.ktorfit.Call<com.example.model.People>\"\n)\n
In the new version of Ktorfit, this behavior has been changed. Now, by default, Ktorfit will keep qualifiedTypename for TypeData in the generated code empty. This means that the qualifiedTypename will not be automatically generated.
val _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<Call<People>>(),\n)\n
However, if you want to keep the old behavior and generate qualifiedTypename, you can set a KSP argument Ktorfit_QualifiedTypeName to true in your build.gradle.kts file.
This change was made to provide more flexibility and control to the developers over the generated code. Please update your code accordingly if you were relying on the automatic generation of qualifiedTypename.
Deprecated the convert function in the SuspendResponseConverter interface See: https://foso.github.io/Ktorfit/migration/#from-170-to-181
! When you still use the deprecated converters because there are use cases which you can\u2019t do with the converter factories, please write a GitHub Issue. The deprecated converters will be removed in one of the upcoming versions
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_6","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_7","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_10","title":"Changed","text":"
Upgrade dependencies: Ktor 2.3.1
"},{"location":"CHANGELOG/#fixed_8","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_5","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_11","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.
@OptIn(InternalKtorfitApi::class)\npublic class _ExampleApiImpl(\nprivate val _ktorfit: Ktorfit,\n) : ExampleApi {\nprivate val _helper: KtorfitConverterHelper = KtorfitConverterHelper(_ktorfit)\n\noverride suspend fun exampleGet(): People {\nval _ext: HttpRequestBuilder.() -> Unit = {\nmethod = HttpMethod.parse(\"GET\")\nurl{\ntakeFrom(_ktorfit.baseUrl + \"/test\")\n}\n}\nval _typeData = TypeData.createTypeData(\ntypeInfo = typeInfo<People>(),\n)\nreturn _helper.suspendRequest(_typeData,_ext)!!\n}\n}\n\npublic class _ExampleApiProvider : ClassProvider<ExampleApi> {\noverride fun create(_ktorfit: Ktorfit): ExampleApi = _ExampleApiImpl(_ktorfit)\n}\n\npublic fun Ktorfit.createExampleApi(): ExampleApi = _ExampleApiImpl(this)\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(jvmKtorfit))\n
The create() function is used, checks that the compiler plugin replaced the default value
public fun <T> create(data: T? = null): T {\nif (data == null) {\nthrow IllegalArgumentException(ENABLE_GRADLE_PLUGIN)\n}\nreturn data\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 it in the Ktorfit config to change this
"},{"location":"configuration/#ktorfit-builder","title":"Ktorfit Builder","text":""},{"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
"},{"location":"development/","title":"Development","text":""},{"location":"development/#update-ktorfit-for-new-kotlin-version","title":"Update Ktorfit for new Kotlin version","text":"
Bump kotlin in libs.versions
Change ktorfitCompiler in libs.versions to KTORFIT_VERSION-NEW_KOTLIN_VERSION
Add the Ktorfit-lib to your common module. You can find all available versions here
val ktorfitVersion = \"2.1.0\"\n\nsourceSets {\nval commonMain by getting{\ndependencies{\nimplementation(\"de.jensklingenberg.ktorfit:ktorfit-lib:$ktorfitVersion\")\n}\n}\n
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
Ktorfit is based on Ktor clients 2.3.12. 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.12
"},{"location":"knownissues/","title":"Known Issues","text":""},{"location":"knownissues/#kmp-project-with-single-target","title":"KMP project with single target","text":"
Unresolved reference for API class
When you have a KMP project with a single target, IntelliJ will find the generated \u201ccreate\u201d extension function (e.g. ktorfit.createExampleApi()) in your common module, but the compilation will fail because of an \u201cUnresolved reference\u201d error. In that case, you have to use ktorfit.create<ExampleApi>() to make it work, even though it\u2019s already deprecated.
Kotlin handles the compilation of a KMP project with a single target differently than with multiple targets.
"},{"location":"migration/#from-170-to-181","title":"From 1.7.0 to 1.8.1","text":""},{"location":"migration/#suspendresponseconverter","title":"SuspendResponseConverter","text":"
Implement override suspend fun convert(result: KtorfitResult)
public suspend fun convert(result: KtorfitResult): T {\nreturn when (result) {\nis KtorfitResult.Failure -> {\nthrow result.throwable // Or do something with the throwable\n}\n\nis KtorfitResult.Success -> {\nval response = result.response\n//Put the code that was in your other convert function here\n}\n}\n}\n
Redirect the deprecated function to the new function:
override suspend fun convert(response: HttpResponse): Any {\nreturn convert(KtorfitResult.Success(response))\n}\n
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.createExampleApi()\n
Next we use the Ktorfit builder to create a Ktorfit instance, and set the base url. After compiling the project we can then use the generated extension 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.
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.