Search code examples
djangokotlinpostrequestktor

Fail to serialize body, when trying to send a post request with kotlin ktor to django rest API


I'm getting the following error, when I try to make a post request to my django rest API with ktor

Error: Fail to serialize body. Content has type: class com.example.watchwithmemobile.domain.dto.user.UserPostRequest (Kotlin reflection is not available), but OutgoingContent expected.

If you expect serialized body, please check that you have installed the corresponding feature(like Json) and set Content-Type header.

I'm trying to get the username, email, password, password_check from a composable textField in kotlin, then within ktor to send an HTTP post request to my django REST API. However, I get the errors listed above. I'm catching the exception in the PostServiceImplementation as custom exception, I also have the 4xx exceptions catcher. I'm currently using Ktor 1.6.3, I do not want to migrate to version 2.x.x.

The create user view in django accepts:

username = request.data.get('username')
email = request.data.get('email')
password = request.data.get('password')
password_check = request.data.get('password_check')

and it is accessed by http://127....../user/register its response is a {'Actuvation': 'Account created'}

in kotlin, the Response/Request look as follows:

data class UserPostResponse (
    val activation: String
)

data class UserPostRequest(
    val username: String,
    val email: String,
    val password: String,
    val password_check: String
)

and the post service implementation:

override suspend fun createUser(postRequest: UserPostRequest): UserPostResponse? {
        return try {
            client = HttpClient()
            client.post<UserPostResponse> {
                url(HttpRoutes.REGISTER) // 127.....:8080/user/register
                contentType(ContentType.Application.Json)
                body = postRequest
            }
        } catch (exception: ClientRequestException) {
            // 4xx exception
            println("ClientError: ${exception.response.status.description}")
            null
        } catch (exception: Exception) {
            println("Error: ${exception.message}")
            null
        }
    }

features

client = HttpClient(Android) {
            // all features here, jsonSerialization, authentication etc
            install(Logging) {
                level = LogLevel.ALL
            }

            install(JsonFeature) {
                serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
                    prettyPrint = true
                    isLenient = true
                    acceptContentTypes = listOf(ContentType.Any)
                })
            }
        }
    )
}

}


Solution

  • I have been using Ktor 1.6.3, I have updated the version of Ktor to the current latest - 2.3.4. There is the feature ContentNegotiation and serialization, install it as a feature following the official Ktor guide - https://ktor.io/docs/serialization.html. The problem is gone now..