IT272 Mobile Application Development

Mobile Application DevelopmentUnit 716 min read

Networking & Web Services: APIs, HTTP, JSON, REST, Retrofit, Firebase

Unit 7 of Mobile Application Development covers how mobile apps connect to servers—HTTP/HTTPS protocols, RESTful APIs, JSON/XML data formats, Retrofit for Android networking, Firebase Realtime Database, and error handling in real-world scenarios like eSewa payments or Daraz order tracking.

TAKEAWAYS:

  • Mobile apps use HTTP/HTTPS to communicate with servers via REST APIs (GET/POST/PUT/DELETE) or Firebase Realtime Database for live updates.
  • JSON is the standard format for exchanging structured data between apps and servers (e.g., Daraz’s product listings).
  • Retrofit simplifies Android networking by converting API calls into Java/Kotlin methods (used in Khalti’s payment verification).
  • Firebase provides authentication, cloud storage, and real-time sync without managing your own backend (e.g., Pathao’s driver tracking).
  • Error handling (timeouts, 4xx/5xx codes) is critical—Ncell’s app shows "Service Unavailable" for 503 errors.
  • Security requires HTTPS, input validation, and OAuth tokens (e.g., NEPSE’s secure login via Google/Facebook).

1. Why Networking in Mobile Apps?

Mobile apps rarely work alone—they fetch data, send updates, or interact with users via servers. For example:

  • eSewa uses APIs to verify user accounts and process payments.
  • Daraz loads product details from its backend via HTTP requests.
  • Pathao tracks driver locations in real-time using Firebase.

How Apps Connect to Servers

Apps act as clients that send requests to servers (remote computers hosting data or services). The connection follows these steps:

  1. Client (your app) sends a request (e.g., "Show me product ID 123").
  2. Server processes the request (e.g., fetches product details from a database).
  3. Server sends a response (e.g., JSON data with product name, price, and stock).
  4. Client displays the data (e.g., Daraz shows the product page).

2. HTTP/HTTPS: The Language of the Web

HTTP (HyperText Transfer Protocol) is the foundation of data exchange on the web. HTTPS adds security (encryption) using SSL/TLS.

HTTP RequestForward RequestQueryJSON Response200 OK + DataDisplay DataMobile App (Client)InternetWeb ServerDatabase
HTTP request-response cycle for Daraz product fetch (GET /api/products/123)

Key Concepts

Term Description Example
Request A message from client to server (e.g., fetch user data). GET /api/user/123
Response Server’s reply (status code + data). 200 OK + JSON user profile
Methods Actions the client can perform:
- GET Retrieve data (no side effects). Load a product page.
- POST Send data to create/update (e.g., submit a form). Place an order on Daraz.
- PUT Replace entire resource (rare in mobile apps). Update user profile.
- DELETE Remove a resource. Delete a saved cart item.
Status Codes Server’s response status:
- 2xx Success (e.g., 200 OK). Data loaded successfully.
- 4xx Client error (e.g., 404 Not Found). Invalid product ID.
- 5xx Server error (e.g., 500 Internal Server Error). Daraz’s server is down.

How HTTP Works (Step-by-Step)

sequenceDiagram
    participant App as Mobile App
    participant Internet as Internet
    participant Server as Web Server
    participant Database as Database

    App->>Internet: GET /api/products/123
    Internet->>Server: Forward request
    Server->>Database: Query for product ID 123
    Database-->>Server: Return product data (JSON)
    Server-->>Internet: 200 OK + JSON
    Internet-->>App: Display product details
    note right of App: Request includes headers (e.g., Accept: application/json)

Real-World Example: Daraz Order Placement

  1. You tap "Buy Now" on a product.
  2. The app sends a POST request to Daraz’s server with your cart details.
  3. Server validates payment, checks stock, and sends a 200 OK with order confirmation.
  4. App shows "Order Placed!" and updates your order history.

3. RESTful APIs: Designing Clean Interfaces

REST (Representational State Transfer) is an architectural style for designing APIs. Key principles:

  • Stateless: Each request contains all needed info (no server-side memory).
  • Resource-based: Data is accessed via URLs (e.g., /users/123).
  • Standard methods: Use GET, POST, etc.
profileorders123456usersdetailsreviews123789productsorders/api
REST API resource hierarchy (eSewa user profile endpoint with nested resources)

Example: eSewa API for Payment

Endpoint Method Description Example Request
/api/payment/init POST Start a payment session. { "amount": 500, "user_id": "123" }
/api/payment/verify POST Verify payment after user returns. { "transaction_id": "abc123" }
/api/balance GET Fetch user’s eSewa balance. None (just /api/balance)

JSON: The Universal Data Format

Servers send data in JSON (JavaScript Object Notation), a lightweight text format. Example response from Daraz:

{
  "product_id": 123,
  "name": "Smartphone X",
  "price": 49999,
  "stock": 10,
  "images": ["img1.jpg", "img2.jpg"]
}

Why JSON?

  • Easy to read/write (human and machine).
  • Used by 90% of APIs (including Google Maps, Twitter, and Firebase).
  • Parsed in Android using Gson or Jackson.
0user1product
Example JSON structure showing nested objects and arrays (eSewa user profile and product details)

4. Retrofit: Simplifying Android Networking

Retrofit is a library that converts API calls into simple Java/Kotlin methods. No need to manually handle HTTP requests!

sequenceDiagram
    participant App as Android App
    participant Retrofit as Retrofit Library
    participant API as Daraz API Server
    App->>Retrofit: api.getProduct(123)
    Retrofit->>API: GET /api/products/123
    API-->>Retrofit: 200 OK + JSON
    Retrofit-->>App: Product object
    note right of API: No manual HTTP handling

How Retrofit Works

  1. Define an interface for your API.
  2. Use @GET, @POST, etc., to map methods to API endpoints.
  3. Retrofit handles:
    • HTTP requests/responses.
    • JSON parsing (with Gson).
    • Error handling.

Example: Fetching Products from Daraz

// Step 1: Define API interface
interface DarazApi {
    @GET("api/products/{id}")
    suspend fun getProduct(@Path("id") productId: Int): Product

    @POST("api/orders")
    suspend fun placeOrder(@Body order: Order): OrderConfirmation
}

// Step 2: Create Retrofit instance
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.daraz.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val api = retrofit.create(DarazApi::class.java)

// Step 3: Use the API
GlobalScope.launch {
    try {
        val product = api.getProduct(123)
        Log.d("Daraz", "Product: ${product.name}")
    } catch (e: Exception) {
        Log.e("Daraz", "Error: ${e.message}")
    }
}

Trace: Retrofit Request Flow

Step Action State After Step
1 api.getProduct(123) called. Retrofit builds GET /api/products/123.
2 Network call starts. Request sent over HTTPS.
3 Server responds with 200 OK + JSON. JSON parsed into Product object.
4 product.name logged. App displays "Smartphone X".
5 If server returns 500, catch block runs. Logs "Error: Server unavailable".

5. Firebase: Backend for Mobile Apps

Firebase provides real-time databases, authentication, and cloud storage without managing servers. Used by:

  • Pathao: Tracks driver locations in real-time.
  • Khalti: Handles payment status updates instantly.
  • Ncell: Syncs user profiles across devices.
0user1231—2order4563product123
Firebase Realtime Database structure (Pathao order tracking with timestamps and nested data)

Firebase Realtime Database

  • Data is stored as a JSON tree.
  • Changes sync automatically across all connected clients.
  • Example structure for a chat app:
    {
      "users": {
        "user1": { "name": "Alice", "status": "online" },
        "user2": { "name": "Bob", "status": "offline" }
      },
      "messages": {
        "msg1": { "text": "Hi!", "sender": "user1", "timestamp": 123456789 }
      }
    }
    

Example: Pathao Driver Tracking

graph TD
    A["Driver App"] -->|"Updates every 5s"| B["Firebase Database"]
    B -->|"Real-time sync"| C["Dispatcher App"]
    C -->|"Shows live location"| D["Dispatcher Dashboard"]

How it works:

  1. Driver’s app sends GPS updates to Firebase every 5 seconds.
  2. Firebase notifies all connected dispatcher apps instantly.
  3. Dispatchers see live driver locations on their dashboard.

Firebase vs. REST APIs

Feature Firebase Realtime Database REST API (e.g., Retrofit)
Sync Automatic, real-time updates. Manual polling (e.g., GET /live).
Use Case Live data (chat, tracking). Static data (products, profiles).
Setup Easier (no server management). Requires backend development.
Scalability Good for small-to-medium apps. Better for large-scale systems.
Real-time sync (WebSocket)HTTP requestsAutomatic syncManual queriesMobile AppFirebase Realtime DBREST API ServerDatabase
Comparison of real-time data flow between Firebase and REST API architectures

6. Handling Errors Like a Pro

Networking fails—always plan for it. Common errors and fixes:

Error Type Cause Example Fix
404 Not Found Invalid URL or resource. GET /api/invalid-endpoint Check API docs for correct URL.
401 Unauthorized Missing/auth invalid token. Khalti login fails. Verify OAuth token or session.
500 Server Error Server crashed. Daraz app shows "Server Down". Retry with exponential backoff.
Timeout Slow network. Ncell app hangs on data load. Set timeout (e.g., 10 seconds).
No Internet Device offline. eSewa payment fails. Show "Check connection" toast.

Example: Retry Logic for Daraz Orders

fun placeOrderWithRetry(order: Order, maxRetries: Int = 3): OrderConfirmation {
    var lastException: Exception? = null
    repeat(maxRetries) { attempt ->
        try {
            return api.placeOrder(order)
        } catch (e: Exception) {
            lastException = e
            if (attempt < maxRetries - 1) {
                delay((attempt + 1) * 1000) // Wait 1s, 2s, 3s...
            }
        }
    }
    throw lastException ?: IOException("Unknown error")
}

7. Security Best Practices

Never expose sensitive data or trust user input blindly.

Risk Solution
Man-in-the-Middle Always use HTTPS (not HTTP).
SQL Injection Use parameterized queries (never concatenate SQL strings).
Token Theft Store OAuth tokens securely (Android’s EncryptedSharedPreferences).
Data Leaks Validate all server responses (check for null or malformed JSON).

Example: Secure API Call in Khalti

@POST("api/payments")
suspend fun processPayment(
    @Body paymentData: PaymentData,
    @Header("Authorization") token: String
): PaymentResponse
  • Token is fetched securely from SharedPreferences.
  • HTTPS ensures payment data isn’t intercepted.

In the Real World

  1. eSewa Payments

    • Idea Used: REST API + OAuth 2.0
    • How: When you pay a bill, eSewa’s app sends a POST request to eSewa’s server with your bank details and amount. The server validates the payment via OAuth tokens and returns a 200 OK if successful. If the bank declines, it returns a 402 Payment Required error.
  2. Pathao Driver Tracking

    • Idea Used: Firebase Realtime Database
    • How: Every Pathao driver’s app sends their live location (latitude/longitude) to Firebase every 5 seconds. Firebase automatically syncs this data to all connected dispatcher apps, so dispatchers see real-time updates without refreshing.
  3. Daraz Order Queue

    • Idea Used: HTTP Status Codes + Retry Logic
    • How: When you place an order, Daraz’s app sends a POST request to the server. If the server is busy (503 error), the app retries after 2 seconds. If stock is low (409 Conflict), it shows "Out of stock—try again later."

Exam Tip

  1. API Design Questions

    • Expect questions on REST principles (e.g., "Why is /users better than /getUsers?").
    • Trace a request: Draw a sequence diagram for a payment flow (client → server → database → response).
  2. Retrofit Code

    • Know how to:
      • Define an interface with @GET, @POST.
      • Add a ConverterFactory (e.g., GsonConverterFactory).
      • Handle errors with try-catch.
  3. Firebase vs. REST

    • Compare when to use Firebase (real-time) vs. REST (static data).
    • Example: "Would you use Firebase for a stock trading app? Why/why not?"
  4. Error Handling

    • Always include timeout handling and retry logic in your answers.
    • Example: "How would you handle a 500 error when fetching NEPSE stock prices?"
  5. Security

    • Mention HTTPS, input validation, and secure storage for tokens.
    • Example: "How would you secure a Khalti payment API call?"

Practice Questions

  1. Draw a sequence diagram for a user logging into eSewa via Google OAuth.
  2. Write a Retrofit interface for a weather app that fetches forecasts by city name.
  3. Explain why Firebase Realtime Database is better than polling a REST API for live chat messages.
  4. How would you modify the Daraz order placement code to handle a 409 Conflict (out of stock) error?

In the real world

  • Pathao uses Firebase Realtime Database to track driver locations in real-time, updating the app’s live map every 2 seconds via HTTP WebSocket connections (Firebase’s built-in feature).
  • Khalti secures payment verification by sending encrypted POST requests to its API with OAuth tokens, handling 401 Unauthorized errors if the token expires.
  • Ncell’s app shows a 503 Service Unavailable toast when the server is down, using Retrofit’s onFailure() callback to display user-friendly error messages.

Based on the TU BIM syllabus for Mobile Application Development (IT272), unit 7.

Discussion

Loading…