Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 13 Theory – Web Services – Accessing and Creating

Week 13 – Web Services: Accessing and Creating · 90 min read · 28 MCQs to check yourself

Traversy Media – What is a RESTful API? Explanation of REST and HTTP

JavaScript Mastery – Build a REST API with Node.js and Express (CRUD)

1. What is a web service?

A web service is a software system designed for machine-to-machine communication over a network, using standard web protocols (HTTP/HTTPS) and data formats (XML, JSON). It lets apps written in different languages and platforms (Android/Kotlin, iOS/Swift, web/JavaScript) share one back end – the same database, business rules and users.

 Android app ─┐                      ┌── Database (MySQL/PostgreSQL/MongoDB)
 iOS app ─────┼── HTTPS + JSON ──► Web service / API server ──┤
 Website ─────┘                      └── Other services (email, payment, SMS)

Client–server architecture: the mobile app (client) sends requests; the server processes them and returns responses. Benefits: data shared between users and devices, heavy processing on the server, secrets (DB passwords, API keys) stay on the server, apps stay small.

2. Types of web services: SOAP and REST

SOAP (Simple Object Access Protocol)

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Body>
    <GetStudent><RollNo>23-014</RollNo></GetStudent>
  </soap:Body>
</soap:Envelope>

REST (REpresentational State Transfer)

Feature SOAP REST
Type Protocol Architectural style
Format XML only JSON (also XML, text)
Description WSDL OpenAPI/Swagger (optional)
Transport HTTP, SMTP… HTTP
Message size Heavy Light
Speed / mobile friendliness Slower Faster, ideal for mobile
State Can be stateful Stateless
Security WS-Security built in HTTPS + tokens (OAuth 2.0, JWT)
Caching No HTTP caching

Other API styles (awareness)

3. REST API design principles

REST constraints

  1. Client–server – UI separated from data storage.
  2. Stateless – each request contains all needed information (e.g. a token); the server keeps no session between requests.
  3. Cacheable – responses state whether they can be cached.
  4. Uniform interface – resources identified by URIs, manipulated through representations (JSON), standard methods.
  5. Layered system – load balancers, proxies and gateways can sit in between.
  6. (Optional) Code on demand.

Designing endpoints (resources are nouns, methods are verbs)

Operation Method + endpoint Success code
List students GET /api/students 200
One student GET /api/students/7 200 (404 if missing)
Search/filter GET /api/students?semester=5&page=2 200
Create POST /api/students + JSON body 201 Created
Replace PUT /api/students/7 200
Partial update PATCH /api/students/7 200
Delete DELETE /api/students/7 204 No Content
Nested resource GET /api/students/7/courses 200

Good practice: plural nouns (/students, not /getStudents), lowercase with hyphens, versioning (/api/v1/...), pagination, consistent error JSON:

{ "error": "VALIDATION_FAILED", "message": "Email is required" }

Idempotent methods give the same result if repeated: GET, PUT, DELETE (POST is not idempotent – repeating it creates duplicates).

4. Accessing web services securely

Concern Practice
Encryption HTTPS (TLS) always; Android blocks cleartext HTTP by default
Authentication User logs in → server returns a token (e.g. JWT – JSON Web Token); app sends Authorization: Bearer <token> header with each request
Authorisation Server checks what this user may do (role, ownership)
Third-party login OAuth 2.0 / OpenID Connect (Sign in with Google), Credential Manager on Android (passkeys, passwords, Google sign-in)
API keys Identify the app/project, not the user; restrict them; never ship secret keys in the APK – call your own backend
Token storage Encrypt with Android Keystore; never log tokens
Input validation Validate on the server too – never trust the client
Rate limiting Server limits requests to stop abuse
Certificate pinning (Advanced) trust only your server's certificate

Accessing an authenticated API with Retrofit

public interface StudentApi {
    @POST("auth/login") Call<LoginResponse> login(@Body LoginRequest body);   // returns a token
    @GET("students") Call<List<Student>> students(@Header("Authorization") String auth);
}
// usage: after login succeeds, keep the token and send it with every request
// api.students("Bearer " + token).enqueue(callback);

An OkHttp Interceptor can add the header automatically to every request.

Response handling

@GET("students/{id}") Call<Student> student(@Path("id") int id);

api.student(7).enqueue(new Callback<Student>() {
    @Override
    public void onResponse(Call<Student> call, Response<Student> r) {
        if (r.isSuccessful() && r.body() != null) show(r.body());
        else if (r.code() == 404) toast("Not found");
        else toast("Error " + r.code());
    }
    @Override
    public void onFailure(Call<Student> call, Throwable t) { toast("No internet"); }
});

5. Creating a REST web service

A web service is built on a server with a back-end language/framework and a database:

Stack Language
Node.js + Express JavaScript/TypeScript
PHP + Laravel (or plain PHP + MySQL – common in Pakistan) PHP
Python + Flask / Django REST Framework / FastAPI Python
Java/Kotlin + Spring Boot / Ktor Java/Kotlin
ASP.NET Core Web API C#
Firebase / Supabase (BaaS) No server code needed for basic CRUD

Example: a minimal REST API in Node.js + Express

// npm init -y && npm install express
const express = require("express");
const app = express();
app.use(express.json());                       // parse JSON bodies

let feedback = [{ id: 1, name: "Ali", message: "Wi-Fi is slow in lab 3" }];

app.get("/api/feedback", (req, res) => res.json(feedback));          // READ all

app.get("/api/feedback/:id", (req, res) => {                          // READ one
  const item = feedback.find(f => f.id == req.params.id);
  item ? res.json(item) : res.status(404).json({ error: "Not found" });
});

app.post("/api/feedback", (req, res) => {                             // CREATE
  const { name, message } = req.body;
  if (!message) return res.status(400).json({ error: "Message required" });
  const item = { id: feedback.length + 1, name, message };
  feedback.push(item);
  res.status(201).json(item);
});

app.delete("/api/feedback/:id", (req, res) => {                       // DELETE
  feedback = feedback.filter(f => f.id != req.params.id);
  res.status(204).end();
});

app.listen(3000, () => console.log("API running on http://localhost:3000"));

Run with node server.js. From the Android emulator, the computer's localhost is http://10.0.2.2:3000/ (because localhost inside the emulator means the emulator itself). For local HTTP testing allow cleartext only for that host with a network security config – production must use HTTPS.

Example: PHP + MySQL endpoint (classic shared hosting)

<?php // feedback.php
header("Content-Type: application/json");
$db = new mysqli("localhost", "user", "pass", "campus");
if ($_SERVER["REQUEST_METHOD"] === "GET") {
    $rows = $db->query("SELECT id, name, message FROM feedback")->fetch_all(MYSQLI_ASSOC);
    echo json_encode($rows);
} elseif ($_SERVER["REQUEST_METHOD"] === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    $stmt = $db->prepare("INSERT INTO feedback(name, message) VALUES (?, ?)");  // prepared = no SQL injection
    $stmt->bind_param("ss", $data["name"], $data["message"]);
    $stmt->execute();
    http_response_code(201);
    echo json_encode(["id" => $stmt->insert_id]);
}

Note the prepared statement – it prevents SQL injection.

Backend-as-a-Service option

Firebase (Firestore database, Authentication, Cloud Functions, Cloud Messaging) or Supabase (PostgreSQL with an automatic REST API, auth, row-level security) – the app calls their SDK/REST endpoints; you write rules instead of a full server.

Layers of a typical back end

Route/controller (receives request) → validation → service/business logic → data access (ORM/SQL) → database; middleware for authentication, logging and error handling.

6. Testing, documenting and hosting APIs

Tool / step Purpose
Postman / Insomnia / Thunder Client (VS Code) Send GET/POST/PUT/DELETE requests, set headers and JSON bodies, see status and response
curl Command-line requests: curl -X POST -H "Content-Type: application/json" -d "{...}" URL
OpenAPI / Swagger Machine-readable API documentation and interactive test page
JSONPlaceholder, ReqRes, DummyJSON Free fake APIs for practising
Android Studio Network Inspector See your app's real requests
Hosting Render, Railway, Vercel/Netlify functions, cloud VMs (AWS, Azure, GCP), shared PHP hosting; use a domain with HTTPS (Let's Encrypt)
Monitoring Logs, uptime checks, error tracking

Typical development workflow: design endpoints → build server → test each endpoint in Postman → document (Swagger) → deploy with HTTPS → consume from the Android app with Retrofit → handle errors and loading in the UI.

Short and long questions

1. What are web services? Compare SOAP and RESTful web services in detail and explain the principles of REST API design with examples of endpoints and status codes.

Model answer

A web service is a software component accessible over a network through standard web protocols that lets heterogeneous applications exchange data. In mobile computing it forms the back end shared by Android, iOS and web clients (client–server architecture).

SOAP: a W3C protocol where every message is an XML envelope (Envelope, Header, Body, Fault); operations are described in a WSDL file; usually sent with HTTP POST; supports WS-Security, transactions and reliable messaging; heavy and verbose; common in banking and legacy enterprise systems.

REST: an architectural style by Roy Fielding (2000). Resources are identified by URLs and manipulated with HTTP methods; representations are usually JSON; communication is stateless and responses can be cached. It is lightweight, fast and easy to consume from mobile apps.

Comparison: protocol vs style; XML only vs JSON/XML; WSDL vs optional OpenAPI; heavy vs light; WS-Security vs HTTPS + OAuth/JWT; can be stateful vs stateless; not cacheable vs HTTP caching.

REST design: constraints – client–server, stateless, cacheable, uniform interface, layered system. Endpoints use nouns and methods: GET /api/students (200), GET /api/students/7 (200 or 404), POST /api/students (201), PUT/PATCH /api/students/7 (200), DELETE /api/students/7 (204), filtering GET /api/students?semester=5. Use versioning (/api/v1), pagination, consistent JSON error bodies (400 validation, 401 unauthenticated, 403 forbidden, 500 server error) and HTTPS everywhere.

2. Differentiate between SOAP and REST.

Model answer

SOAP is a protocol using XML envelopes described by WSDL, heavier, with built-in WS-Security and possibly stateful. REST is an architectural style using resources identified by URLs and standard HTTP methods, usually exchanging lightweight JSON, stateless and cacheable – better suited for mobile apps.

3. Define web service. Why do mobile apps use web services?

Model answer

A web service is a software system that allows machine-to-machine interaction over a network using standard protocols (HTTP) and formats (JSON/XML). Mobile apps use them to share one back end (database, business logic, users) across Android, iOS and web, keep heavy processing and secrets on the server, and synchronise data between devices.

4. Design REST endpoints for a feedback resource.

Model answer

GET /api/feedback (list, 200), GET /api/feedback/5 (one, 200/404), POST /api/feedback (create, 201), PUT or PATCH /api/feedback/5 (update, 200), DELETE /api/feedback/5 (delete, 204).

5. List the constraints of REST.

Model answer

Client–server separation, statelessness, cacheability, uniform interface (resources identified by URIs and manipulated through representations with standard methods), layered system, and optional code-on-demand.

6. How does token-based authentication work in mobile apps?

Model answer

The user logs in by sending credentials over HTTPS; the server verifies them and returns a signed token (e.g. JWT). The app stores it securely (Keystore-encrypted) and sends it in the Authorization: Bearer header of later requests; the server validates the token on each stateless request and rejects expired or invalid ones with 401.

7. Why does the Android emulator use 10.0.2.2 to reach a local server?

Model answer

Inside the emulator, localhost/127.0.0.1 refers to the emulator itself. Android's emulator maps 10.0.2.2 to the host computer's loopback interface, so a server running on the PC at port 3000 is reached at http://10.0.2.2:3000.

8. Name four technologies used to create web services.

Model answer

Node.js with Express, PHP with Laravel (or plain PHP + MySQL), Python with Django REST Framework/FastAPI/Flask, Java/Kotlin with Spring Boot or Ktor, ASP.NET Core Web API (C#); or Backend-as-a-Service platforms like Firebase and Supabase.

9. How are APIs tested and documented?

Model answer

Endpoints are tested with tools like Postman, Insomnia, Thunder Client or curl by sending requests with methods, headers and JSON bodies and checking status codes and responses; they are documented with OpenAPI/Swagger, which also provides interactive test pages. The app's real traffic can be checked with Android Studio's Network Inspector.

10. Explain how to create a simple RESTful web service and access it from an Android app. Include server code (Node.js/Express or PHP), testing with Postman, security considerations and the Android client code with Retrofit.

Model answer

Server (Node.js + Express): create a project (npm init, npm install express), enable JSON parsing with app.use(express.json()), and define routes: app.get("/api/feedback", ...) returns the list with res.json; app.get("/api/feedback/:id", ...) returns one or 404; app.post("/api/feedback", ...) validates req.body (400 if invalid), saves the item and returns 201 with the new object; app.delete("/api/feedback/:id", ...) returns 204. Start with app.listen(3000). Real services store data in a database (MySQL/PostgreSQL/MongoDB) using prepared statements or an ORM. An equivalent PHP endpoint reads $_SERVER["REQUEST_METHOD"], uses mysqli prepared statements and echoes json_encode results.

Testing: use Postman (or curl) to send GET/POST/DELETE requests with Content-Type: application/json, check status codes and bodies, and document the API with OpenAPI/Swagger. Deploy to a host (Render, Railway, cloud VM, PHP hosting) with HTTPS.

Security: HTTPS only; authentication with tokens (JWT Bearer) or OAuth; authorisation checks; server-side validation; rate limiting; secrets kept on the server; protection against SQL injection.

Android client (Retrofit): public class Feedback { public int id; public String name, message; }; public interface FeedbackApi { @GET("api/feedback") Call<List<Feedback>> all(); @POST("api/feedback") Call<Feedback> send(@Body Feedback f); }; build Retrofit with the base URL (http://10.0.2.2:3000/ for a local server during development, the HTTPS domain in production) and GsonConverterFactory; call them with enqueue() and handle onResponse/onFailure, show a progress indicator and display results in a RecyclerView; add the INTERNET permission.

This lesson ends with a quiz of 28 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 12 Lab 12 – Display Data from an API Using Retrofit and a RecyclerView · Next: Week 13 Lab 13 – Build a Countdown Timer App

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester