{"id":874,"date":"2026-10-21T13:47:00","date_gmt":"2026-10-21T11:47:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=874"},"modified":"2026-10-20T22:26:18","modified_gmt":"2026-10-20T20:26:18","slug":"retrofit-204-null-body-crash","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/retrofit-204-null-body-crash\/","title":{"rendered":"Retrofit 204 Crash: Response Was Null but Response Body Type Was Declared as Non-Null"},"content":{"rendered":"<p>Retrofit throws <code>KotlinNullPointerException<\/code> when a suspend function gets a 204 or 205. The message says the &#8220;response body type was declared as non-null&#8221;. The crash comes from two separate behaviors in Retrofit. First, Retrofit never runs your converter for those two status codes. It hands back a successful response with a <code>null<\/code> body. Second, Retrofit can&#8217;t read Kotlin nullability on a suspend function&#8217;s return type. So adding <code>?<\/code> changes nothing. The call still goes through the non-null path that throws. A typical trigger is a backend change. A DELETE endpoint that used to return JSON starts returning 204 No Content. Every delete then crashes. The fix depends on the endpoint. If it never returns a body, declare the function as returning <code>Unit<\/code>. That works on Retrofit 2.10.0 and newer. If it can return a body or a 204, return <code>Response&lt;T&gt;<\/code>. Treat a null body as &#8220;no content&#8221;.<\/p>\n\n<h2>A notes app that crashes on delete after a backend deploy<\/h2>\n\n<p>The running example is a notes app. Deleting a note calls the server, then removes the local row. The server used to answer with a small JSON object. The app code below was written against that contract.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Serializable\ndata class DeleteResult(val id: String, val deleted: Boolean)\n\ninterface NotesApi {\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNote(@Path(\"id\") id: String): DeleteResult\n}\n\nclass NotesRepository(private val api: NotesApi, private val dao: NoteDao) {\n    suspend fun delete(id: String) {\n        api.deleteNote(id)\n        dao.deleteById(id)\n    }\n}<\/pre>\n\n\n<p>Then the backend team tidies up its API. DELETE now returns 204 with no body. That&#8217;s a valid answer. <a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc9110.html#name-204-no-content\" target=\"_blank\" rel=\"noopener\">RFC 9110<\/a> defines 204 as success with no content in the response. No app code changed. The next delete crashes with this.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">kotlin.KotlinNullPointerException: Response from NotesApi.deleteNote was null but response body type was declared as non-null<\/pre>\n\n\n<p>The server has already deleted the note. The exception skips <code>dao.deleteById<\/code>, so the note stays on screen. If the backend answers 404 for a missing note, the user&#8217;s second tap now fails differently.<\/p>\n\n<h2>Retrofit skips the converter and returns a null body for 204 and 205<\/h2>\n\n<p>The first cause sits in <code>OkHttpCall.parseResponse<\/code>. In the <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/blob\/2.11.0\/retrofit\/src\/main\/java\/retrofit2\/OkHttpCall.java#L239-L242\" target=\"_blank\" rel=\"noopener\">Retrofit 2.11.0 source<\/a>, a 204 or 205 closes the raw body and returns early. It builds <code>Response.success(null, rawResponse)<\/code> without calling any converter. The kotlinx.serialization converter never sees the request. So nothing can fail during parsing. Nothing can supply a default object either.<\/p>\n\n<p>This is old, intended behavior. <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/issues\/2867\" target=\"_blank\" rel=\"noopener\">Issue #2867<\/a> was filed in August 2018 and is still open. It asks for 204 and 205 to reach the converter. The response is still a success, because 204 is a 2xx code. So the null body travels on to the code that adapts the call for coroutines.<\/p>\n\n<h2>Why the response body type was declared as non-null error ignores ?<\/h2>\n\n<p>The second cause defeats the obvious fix. For a suspend function, Retrofit picks one of three <code>await<\/code> paths. <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/blob\/2.11.0\/retrofit\/src\/main\/java\/retrofit2\/HttpServiceMethod.java#L40-L70\" target=\"_blank\" rel=\"noopener\"><code>HttpServiceMethod<\/code><\/a> sets a flag for <code>Unit<\/code> and a flag for nullable bodies. The nullable flag starts as <code>false<\/code> and is never set. The line that would set it is a <code>TODO<\/code> comment about reading Kotlin metadata. So any non-<code>Unit<\/code> body type takes the non-null path.<\/p>\n\n<p>That path is <code>await()<\/code> in <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/blob\/2.11.0\/retrofit\/src\/main\/java\/retrofit2\/KotlinExtensions.kt#L31-L60\" target=\"_blank\" rel=\"noopener\"><code>KotlinExtensions.kt<\/code><\/a>. On a successful response with a null body, it builds the <code>KotlinNullPointerException<\/code> above. The message uses the service and method names from the request&#8217;s <code>Invocation<\/code> tag. <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/issues\/3075\" target=\"_blank\" rel=\"noopener\">Issue #3075<\/a>, filed in April 2019, reports that <code>?<\/code> and <code>@Nullable<\/code> both fail to help. It&#8217;s still open. The trunk source still has the same <code>TODO<\/code>.<\/p>\n\n<p>A small repro shows both causes. It uses OkHttp&#8217;s <code>MockWebServer<\/code> 4.12.0, kotlinx.serialization 1.9.0 and Jake Wharton&#8217;s serialization converter 1.0.0. It adds three more declarations of the same endpoint to the <code>NotesApi<\/code> above. Then it calls each one against a 204.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">interface NotesApi {\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNote(@Path(\"id\") id: String): DeleteResult\n\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNoteNullable(@Path(\"id\") id: String): DeleteResult?\n\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNoteUnit(@Path(\"id\") id: String)\n\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNoteResponse(@Path(\"id\") id: String): Response&lt;DeleteResult&gt;\n}\n\nfun main() = runBlocking {\n    val server = MockWebServer().apply { start() }\n    val api = Retrofit.Builder()\n        .baseUrl(server.url(\"\/\"))\n        .addConverterFactory(Json.asConverterFactory(\"application\/json\".toMediaType()))\n        .build()\n        .create(NotesApi::class.java)\n\n    val calls: List&lt;Pair&lt;String, suspend () -&gt; Any?&gt;&gt; = listOf(\n        \"DeleteResult \" to { api.deleteNote(\"n1\") },\n        \"DeleteResult?\" to { api.deleteNoteNullable(\"n1\") },\n        \"Unit         \" to { api.deleteNoteUnit(\"n1\") },\n        \"Response&lt;T&gt;  \" to { api.deleteNoteResponse(\"n1\").let { \"code=${it.code()} body=${it.body()}\" } },\n    )\n    for ((label, call) in calls) {\n        server.enqueue(MockResponse().setResponseCode(204))\n        val result = runCatching { call() }\n        println(\"204 $label -&gt; \" + result.fold({ \"OK $it\" }, { \"${it::class.simpleName}: ${it.message}\" }))\n    }\n    server.shutdown()\n}<\/pre>\n\n\n<p>We built it with <code>kotlinc<\/code> 2.4.20 and ran it on JDK 25 against Retrofit 2.11.0. The output:<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">204 DeleteResult  -&gt; KotlinNullPointerException: Response from NotesApi.deleteNote was null but response body type was declared as non-null\n204 DeleteResult? -&gt; KotlinNullPointerException: Response from NotesApi.deleteNoteNullable was null but response body type was declared as non-null\n204 Unit          -&gt; OK kotlin.Unit\n204 Response&lt;T&gt;   -&gt; OK code=204 body=null<\/pre>\n\n\n<p>The nullable declaration fails exactly like the non-null one. Retrofit 3.0.0 printed the same four lines. Retrofit 2.9.0 differed in one place. Its <code>Unit<\/code> line also threw <code>KotlinNullPointerException<\/code>.<\/p>\n\n<h2>Declare Unit when the endpoint never sends a body<\/h2>\n\n<p>That 2.9.0 result is why the fix has a version floor. The <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/commit\/9eedffd1\" target=\"_blank\" rel=\"noopener\">commit that added the <code>Unit<\/code> path<\/a> names this exact case. It covers suspend functions on responses without a body. It first shipped in Retrofit 2.10.0, released in March 2024. The <a href=\"https:\/\/github.com\/lysine-dev\/retrofit\/blob\/trunk\/CHANGELOG.md\" target=\"_blank\" rel=\"noopener\">changelog<\/a> lists it as support for <code>Unit<\/code> as a response type. A suspend function with no declared return type is a <code>Unit<\/code> function. So the shortest fix is to delete the return type.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">interface NotesApi {\n    \/\/ No body expected. Needs Retrofit 2.10.0 or newer.\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNote(@Path(\"id\") id: String)\n}\n\n\/\/ Only when the same endpoint may answer 200 with JSON or 204 with nothing.\ninterface NotesApiMixed {\n    @DELETE(\"notes\/{id}\")\n    suspend fun deleteNote(@Path(\"id\") id: String): Response&lt;DeleteResult&gt;\n}\n\nsuspend fun NotesApiMixed.deleteOrNull(id: String): DeleteResult? {\n    val response = deleteNote(id)\n    if (!response.isSuccessful) throw HttpException(response)\n    return response.body() \/\/ null on 204 and 205\n}<\/pre>\n\n\n<p>We ran both forms against the same mock server on Retrofit 2.11.0 and 3.0.0. The <code>Unit<\/code> version returned normally on a 204. It did the same on a 200 with an empty body and on a 200 with JSON. A 404 still threw <code>HttpException<\/code>, so real failures still surface. The mixed version returned <code>null<\/code> on the 204 and the parsed <code>DeleteResult<\/code> on the 200.<\/p>\n\n<p>The <code>Unit<\/code> form is the better default for a delete. The repository never read <code>DeleteResult<\/code> anyway. It also keeps working if the backend switches back to 200. Use the <code>Response&lt;T&gt;<\/code> form only when the caller needs the body on some responses. On Retrofit 2.9.0 or older, <code>Response&lt;Unit&gt;<\/code> is the safe choice, because <code>Response&lt;T&gt;<\/code> never goes through the non-null <code>await()<\/code>.<\/p>\n\n<h2>What to say when the stack trace is the whole prompt<\/h2>\n\n<p>In a bug-squash round, you might get the stack trace, the <code>NotesApi<\/code> interface and one line of context. The interviewer says delete broke &#8220;after the backend deploy&#8221; with no app release. Our <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">Android debugging interview post<\/a> covers how that round is scored. Answer in this order.<\/p>\n\n<ol>\n<li>Read the message. Retrofit got a successful response with a null body. The declared type is non-null.<\/li>\n<li>Connect it to the deploy. A successful response with no body points to the backend now sending 204 No Content.<\/li>\n<li>Name the first cause. Retrofit returns a null body for 204 and 205 without calling the converter.<\/li>\n<li>Name the second cause. The suspend adapter can&#8217;t see Kotlin nullability, so <code>DeleteResult?<\/code> takes the same throwing path.<\/li>\n<li>Give the fix. Declare <code>Unit<\/code> on Retrofit 2.10.0 or newer. Use <code>Response&lt;T&gt;<\/code> if the endpoint can still send a body.<\/li>\n<li>Point out the side effect. The server deleted the note. The local delete never ran. Ask whether the repository should treat 404 on delete as success.<\/li>\n<\/ol>\n\n<p>Point 4 rules out the nullable fix before the interviewer suggests it. It also shows you know how Retrofit adapts suspend functions.<\/p>\n\n<h2>Five quick fixes and where each one falls short<\/h2>\n\n<ul>\n<li>&#8220;Make the return type nullable.&#8221; The repro shows <code>DeleteResult?<\/code> throwing the same exception. Retrofit never reads the <code>?<\/code>.<\/li>\n<li>&#8220;Add a null-on-empty converter factory.&#8221; That pattern handles a 200 with an empty body. That case does reach the converter. A 204 returns before any converter runs, so the factory never sees it.<\/li>\n<li>&#8220;Rewrite 204 to 200 in an OkHttp interceptor.&#8221; Issue #2867&#8217;s first reply suggested this in 2018. With a non-null <code>DeleteResult<\/code>, we rewrote 204 to a 200 with a <code>null<\/code> JSON body. The serialization converter then threw <code>JsonDecodingException<\/code> instead. It also changes the status code for every endpoint on that client. Our <a href=\"https:\/\/grindloop.ai\/blog\/okhttp-interceptor-illegalstateexception-closed\/\">post on reading bodies in OkHttp interceptors<\/a> covers a separate trap in that code.<\/li>\n<li>&#8220;Catch <code>KotlinNullPointerException<\/code>.&#8221; It only works if the catch block treats the exception as success. Then a real null-body bug on that call is swallowed too. The fix is to stop declaring a body the server doesn&#8217;t send.<\/li>\n<li>&#8220;Ask the backend to return 200 again.&#8221; That restores the old contract. But 204 was a valid change. The client should accept both.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Retrofit says response body type was declared as non-null on a 204 because it skips the converter and ignores ?. Runnable repro, Unit fix, interview answer.<\/p>\n","protected":false},"author":2,"featured_media":875,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Retrofit 204 Crash: Response Was Null but Response Body Type Was Declared as Non-Null","rank_math_description":"Retrofit says response body type was declared as non-null on a 204 because it skips the converter and ignores ?. Runnable repro, Unit fix, interview answer.","rank_math_focus_keyword":"response body type was declared as non-null","footnotes":""},"categories":[9,6],"tags":[15,87,16,12,57,109,45],"class_list":["post-874","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-networking","tag-android","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-networking","tag-retrofit","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/874","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=874"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/874\/revisions"}],"predecessor-version":[{"id":876,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/874\/revisions\/876"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/875"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=874"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=874"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=874"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}