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:
- Client (your app) sends a request (e.g., "Show me product ID 123").
- Server processes the request (e.g., fetches product details from a database).
- Server sends a response (e.g., JSON data with product name, price, and stock).
- 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.
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
- You tap "Buy Now" on a product.
- The app sends a
POSTrequest to Daraz’s server with your cart details. - Server validates payment, checks stock, and sends a
200 OKwith order confirmation. - 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.
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
GsonorJackson.
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 handlingHow Retrofit Works
- Define an interface for your API.
- Use
@GET,@POST, etc., to map methods to API endpoints. - 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.
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:
- Driver’s app sends GPS updates to Firebase every 5 seconds.
- Firebase notifies all connected dispatcher apps instantly.
- 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. |
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
eSewa Payments
- Idea Used: REST API + OAuth 2.0
- How: When you pay a bill, eSewa’s app sends a
POSTrequest to eSewa’s server with your bank details and amount. The server validates the payment via OAuth tokens and returns a200 OKif successful. If the bank declines, it returns a402 Payment Requirederror.
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.
Daraz Order Queue
- Idea Used: HTTP Status Codes + Retry Logic
- How: When you place an order, Daraz’s app sends a
POSTrequest 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
API Design Questions
- Expect questions on REST principles (e.g., "Why is
/usersbetter than/getUsers?"). - Trace a request: Draw a sequence diagram for a payment flow (client → server → database → response).
- Expect questions on REST principles (e.g., "Why is
Retrofit Code
- Know how to:
- Define an interface with
@GET,@POST. - Add a
ConverterFactory(e.g.,GsonConverterFactory). - Handle errors with
try-catch.
- Define an interface with
- Know how to:
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?"
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?"
Security
- Mention HTTPS, input validation, and secure storage for tokens.
- Example: "How would you secure a Khalti payment API call?"
Practice Questions
- Draw a sequence diagram for a user logging into eSewa via Google OAuth.
- Write a Retrofit interface for a weather app that fetches forecasts by city name.
- Explain why Firebase Realtime Database is better than polling a REST API for live chat messages.
- 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
POSTrequests to its API with OAuth tokens, handling401 Unauthorizederrors if the token expires. - Ncell’s app shows a
503 Service Unavailabletoast when the server is down, using Retrofit’sonFailure()callback to display user-friendly error messages.
Based on the TU BIM syllabus for Mobile Application Development (IT272), unit 7.
Discussion
Loading…