Search code examples
androidkotlingsonretrofit2

Retrofit2: Kotlin POST request with JSON data returning 400


I'm trying to use Retrofit2 instead of raw HttpUrlConnection for my app so I'm testing it and I found first basic problem with it.

I'm trying this on Reques.in testing API to pass json data to it, but its returning HTTP code 400.

object AppAPI {

    private const val baseUrl = "https://reqres.in/api/"

    fun getInstance(): Retrofit {
        return Retrofit.Builder().baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}

interface ApiRegisterUser {
    @Headers(
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json;charset=utf-8"
    )
    @POST("register")
    suspend fun registerUser(@Body userData: UserRegisterData) : Response<UserRegisterResponse>
}

data class UserRegisterData(
    @SerializedName("email") val email: String,
    @SerializedName("password") val password: String
)

Response:

response: error: response: Response{protocol=h2, code=400, message=, url=https://reqres.in/api/register}

So I figured out Error there: There is specific Error in response.errorBody()

Note: Only defined users succeed registration

But not sure what does it mean


Solution

  • While not explicitly mentioned in the documentation, it looks like this dummy REST API server only supports predefined e-mail addresses for the /register endpoint, see the "Hello ReqRes users!" section on https://reqres.in/ for the predefined users.

    So using for example [email protected] as e-mail address seems to work. The password apparently does not matter.