IT272 Mobile Application Development

Mobile Application DevelopmentUnit 710 min read

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

Unit 7 of Mobile Application Development covers how mobile apps connect to servers, parse data, and use web services—explaining HTTP/HTTPS, REST APIs, JSON/XML parsing, Retrofit for Android, Firebase integration, and error handling with real-world examples from eSewa, Daraz, and Ncell.

Core Concepts: Why Mobile Apps Need Networking

Mobile apps rarely work in isolation. They rely on networking to:

  • Fetch data from servers (e.g., user profiles, product listings).
  • Send data to servers (e.g., login credentials, order confirmations).
  • Use third-party services (e.g., Google Maps, payment gateways).

1. Networking Basics: HTTP/HTTPS and Protocols

How HTTP Works

HTTP (HyperText Transfer Protocol) is the foundation of data exchange between clients (mobile apps) and servers. It uses:

  • Request-Response Model: Client sends a request (e.g., GET, POST), server responds with data (e.g., JSON/XML).
  • Status Codes: Indicate success/failure (e.g., 200 OK, 404 Not Found, 500 Server Error).
flowchart TD
    A["Client (Mobile App)"] -->|"HTTP Request"| B["Server"]
    B -->|"HTTP Response"| A

HTTP vs. HTTPS

Feature HTTP HTTPS
Security No encryption (insecure) Encrypted (SSL/TLS)
Port 80 443
Use Case Local testing Production apps (e.g., eSewa)
HTTPS = HTTP + TLS/SSLHTTPHTTPS
HTTPS adds encryption (TLS/SSL) to HTTP for secure communication

Example: When you log in to eSewa, your credentials travel via HTTPS to prevent hacking.


2. RESTful APIs: The Standard for Mobile Backend Communication

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

  • Stateless: Each request contains all needed info (no server-side session storage).
  • Resource-Based: Data is accessed via URLs (e.g., /users/123).
  • Standard Methods: GET, POST, PUT, DELETE.

REST API Workflow

sequenceDiagram
    participant App as Mobile App
    participant API as REST API Server
    App->>API: GET /products (Request)
    API-->>App: JSON Response (Product List)
    App->>API: POST /order (Order Data)
    API-->>App: 200 OK (Confirmation)

Example: Daraz Mobile App

  • Endpoint: GET https://api.daraz.com/products?category=electronics
  • Response: JSON array of products with id, name, price.
  • Use Case: When you browse electronics on Daraz, the app fetches this data dynamically.

3. Data Formats: JSON vs. XML

Feature JSON XML
Syntax Lightweight, key-value pairs Verbose, tag-based
Readability Easy for humans/machines Harder to read
Use Case Modern APIs (e.g., YouTube) Legacy systems (e.g., SOAP)

JSON Example (eSewa Transaction):

{
  "transaction": {
    "id": "TXN12345",
    "amount": 500,
    "status": "completed",
    "timestamp": "2023-10-15T12:00:00Z"
  }
}

XML Example (Ncell Billing):

<transaction>
  <id>TXN12345</id>
  <amount>500</amount>
  <status>completed</status>
</transaction>

4. Android Networking: Retrofit Library

Retrofit simplifies HTTP requests in Android by:

  • Converting JSON/XML to Java objects (POJOs).
  • Handling threading (avoids NetworkOnMainThreadException).

Step-by-Step Retrofit Setup

  1. Add Dependency (build.gradle):
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    
  2. Define API Interface:
    public interface ApiService {
        @GET("products")
        Call<List<Product>> getProducts();
    }
    
  3. Create Retrofit Instance:
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.example.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    ApiService apiService = retrofit.create(ApiService.class);
    
  4. Make a Request:
    apiService.getProducts().enqueue(new Callback<List<Product>>() {
        @Override
        public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
            if (response.isSuccessful()) {
                List<Product> products = response.body();
                // Update UI
            }
        }
        @Override
        public void onFailure(Call<List<Product>> call, Throwable t) {
            Log.e("Error", t.getMessage());
        }
    });
    

Trace: Retrofit Request Flow

Step Action
1 Retrofit parses GET /products endpoint.
2 Thread switches to background (avoids ANR).
3 Server responds with JSON.
4 Gson converts JSON → List<Product> objects.
5 onResponse updates UI (e.g., RecyclerView).

5. Firebase: Real-Time Database for Mobile Apps

Firebase provides:

  • Firestore: NoSQL cloud database (scalable, real-time updates).
  • Authentication: Google/Facebook login (e.g., Pathao driver app).
  • Cloud Functions: Serverless backend logic.

Firestore Data Structure

name: 'John'email: 'john@example.com'orders: [order1, order2]user123user456/users
Firestore nested document structure with user123 expanded

Example: Ncell Recharge App

  • Use Case: Real-time balance updates.
  • Firestore Rule:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
          allow read, write: if request.auth != null;
        }
      }
    }
    
  • Workflow:
    1. User recharges via app → Firestore updates balance field.
    2. All connected devices (e.g., another phone) see the update instantly.

6. Error Handling and Retry Logic

Common network issues:

  • No Internet: NoConnectivityException.
  • Timeout: Server too slow (SocketTimeoutException).
  • Invalid Response: Malformed JSON (JSONException).

Retry Mechanism Example

int maxRetries = 3;
int retryCount = 0;
while (retryCount < maxRetries) {
    try {
        apiService.getProducts().enqueue(callback);
        break; // Success
    } catch (Exception e) {
        retryCount++;
        if (retryCount == maxRetries) {
            showErrorToUser();
        }
    }
}

7. Security Best Practices

Threat Solution
Man-in-the-Middle Always use HTTPS.
Data Leaks Never hardcode API keys; use buildConfigField.
SQL Injection Use parameterized queries (e.g., Room Database).
OAuth Tokens Store tokens securely (e.g., Android Keystore).

Example: Khalti uses OAuth 2.0 for secure payments:

  1. App redirects to Khalti’s login page.
  2. Khalti returns a code → app exchanges it for an access_token.
  3. Token is used for API calls (never stored permanently).

In the Real World

  1. eSewa Mobile App

    • Idea Used: REST API + HTTPS.
    • How: When you pay a bill, the app sends a POST request to eSewa’s server with transaction details. The server validates the request, processes the payment, and returns a JSON response with the receipt.
  2. Daraz Mobile App

    • Idea Used: Retrofit + JSON parsing.
    • How: When you search for "smartphone," the app uses Retrofit to call Daraz’s API (GET /products?query=smartphone). The response is parsed into a List<Product>, which populates the search results dynamically.
  3. Pathao Driver App

    • Idea Used: Firebase Realtime Database.
    • How: When a driver accepts a ride, Firebase updates the rideStatus field for both driver and passenger in real-time. Both users see the status change instantly without refreshing.

Exam Tip

  1. Diagrams Are Key: Draw REST request-response cycles, Retrofit flowcharts, or Firebase data structures. Examiners love visuals!
  2. Code Snippets: Know how to write a Retrofit GET/POST call and handle responses. Always include error handling.
  3. Real-World Mapping: Relate concepts to apps like eSewa (HTTPS), Daraz (Retrofit), or Ncell (Firebase). Example:

    "Explain how Daraz uses Retrofit to fetch product data. Include a code snippet and a trace of the network call."

  4. Common Pitfalls:
    • Forgetting to add Internet permission in AndroidManifest.xml.
    • Not using enqueue() (blocks UI thread).
    • Ignoring HTTPS (fails security checks).
  5. Shortcut for Full Marks:
    • For API questions, show:
      1. Endpoint URL.
      2. HTTP method (GET/POST).
      3. Request/response headers (e.g., Content-Type: application/json).
      4. Sample JSON/XML.
    • For Firebase, draw the database hierarchy and explain security rules.

Practice Question with Solution

Question: "Design a REST API endpoint for a bank app to fetch user transactions. Include the HTTP method, URL, request headers, and a sample JSON response. How would you implement this in Android using Retrofit?"

Solution:

  1. API Design:

    • Method: GET
    • URL: /api/transactions?userId=123&limit=10
    • Headers:
      Authorization: Bearer <token>
      Content-Type: application/json
      
    • Sample Response:
      {
        "transactions": [
          {
            "id": "TXN001",
            "amount": 5000,
            "type": "deposit",
            "date": "2023-10-10"
          }
        ]
      }
      
  2. Retrofit Implementation:

    public interface BankApi {
        @GET("api/transactions")
        Call<TransactionResponse> getTransactions(
            @Query("userId") String userId,
            @Query("limit") int limit,
            @Header("Authorization") String token
        );
    }
    
  3. Usage:

    BankApi api = retrofit.create(BankApi.class);
    api.getTransactions("123", 10, "Bearer token123").enqueue(new Callback<TransactionResponse>() {
        @Override
        public void onResponse(Call<TransactionResponse> call, Response<TransactionResponse> response) {
            if (response.isSuccessful()) {
                List<Transaction> transactions = response.body().getTransactions();
                // Update RecyclerView
            }
        }
    });
    

Visual Trace:

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

Discussion

Loading…