CHAPTER 26
Beginner
REST APIs and JSON Handling
Updated: May 18, 2026
5 min read
# CHAPTER 26
REST APIs and JSON Handling
1. Chapter Introduction
Almost every modern application requires internet access. A weather app fetches forecasts; a social media app fetches posts. Apps communicate with servers using REST APIs (Application Programming Interfaces). The server typically responds with data formatted as JSON (JavaScript Object Notation). In this chapter, we will learn how to use the industry-standard library, Retrofit, alongside Coroutines to fetch data from the internet and convert it directly into Kotlin Data Classes.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand what a REST API and JSON are.
- Understand the role of the Retrofit library.
- Create Data Classes to match JSON structure.
-
Define an API Interface using
@GET.
- Make an asynchronous network request.
3. Understanding JSON
JSON is a text format used to transmit data over the web. It uses Key-Value pairs. Example of a JSON response from a server:
json
4. Creating the Kotlin Data Class
To use this data in Kotlin, we create a Data Class that exactly matches the JSON keys! A library likeGson or Moshi (used alongside Retrofit) will automatically parse the JSON text into this object.
kotlin
5. Defining the API Interface (Retrofit)
Similar to Room DAOs, Retrofit uses an Interface to define the API endpoints. We use annotations like@GET or @POST.
*Crucial: Network requests are slow. We MUST mark them as suspend functions so they run in Coroutines!*
kotlin
6. Setting Up Retrofit
To actually make the request, we must build the Retrofit instance, assign the Base URL, and add a Converter Factory (which translates the JSON text into our Data Class).
kotlin
7. Making the Request
Because the API call is asuspend function, we must launch a Coroutine to execute it. We should also wrap it in a try-catch block, because networks are unreliable (no wifi, airplane mode, server down).
kotlin
8. Common Mistakes
-
Missing Internet Permission: In Android, if you do not add
<uses-permission android:name="android.permission.INTERNET"/>to yourAndroidManifest.xml, your app is strictly blocked from making network requests and will crash.
-
Mismatched Variable Names: If the JSON key is
firstnamebut your data class hasval firstName, the parser will fail and return null. You must either match it exactly, or use annotations like@SerializedName("firstname")to bridge the gap.
9. Best Practices
-
Never hardcode API Keys: If you use a paid API, do not hardcode the key in your Kotlin file. Keep it in a secure
local.propertiesfile or inject it via build configurations.
10. Exercises
*(Theoretical)*-
1.
A server returns
{"username": "dev123", "score": 95}. Write the Kotlin data class to hold this.
-
2.
Write a Retrofit Interface with a
@GET("profile")method that returns this object.
11. MCQs with Answers
Question 1
What is JSON?
Question 2
What is the industry-standard library for making network requests in Kotlin/Android?
Question 3
How do you map JSON data to a Kotlin object?
Question 4
What Retrofit annotation is used to fetch data from a server?
Question 5
Why must Retrofit API methods be marked with the suspend keyword?
Question 6
What does a Converter Factory (like GsonConverterFactory) do in Retrofit?
Question 7
What happens if the internet goes down during a Retrofit request?
Question 8
What permission is mandatory in the Android Manifest to use Retrofit?
Question 9
If a JSON key is "userage", but you want your Kotlin variable to be "userAge", what annotation do you use?
Question 10
How is Retrofit usually instantiated in an application?
12. Interview Questions
- Q: Describe the architecture of a Retrofit setup. How do Data Classes, the API Interface, and Coroutines work together?
-
Q: Why do we use
try-catchblocks around network requests? Give two examples of exceptions that might occur. (Answer: No internet connectionUnknownHostException, or Server TimeoutSocketTimeoutException).
13. Summary
Connecting to the internet is a fundamental requirement for modern applications. By utilizing Retrofit and Gson, Kotlin developers can avoid manual, error-prone JSON parsing. Furthermore, by executing Retrofit requests assuspend functions inside Coroutines, we ensure that our applications remain buttery-smooth and responsive, regardless of how slow the network connection is.