Kahibaro
Discord Login Register

18.2 REST APIs

Understanding REST in Android Networking

In Android development most modern web services you call are REST APIs. This chapter focuses on how REST shapes the way you send requests and receive responses. You will later combine this knowledge with specific libraries, but here you learn the concepts that REST introduces and how they affect Android apps.

What REST Means

REST stands for Representational State Transfer. It is not a protocol like HTTP, but an architectural style that uses HTTP and other web standards in a consistent way.

In a REST API, your app works with resources. A resource can be a user, a product, a post, or any logical object in the backend. Each resource is identified by a URL, often called an endpoint. For example, https://api.example.com/users can represent a collection of users, and https://api.example.com/users/42 can represent a single user with id 42.

The important idea is that instead of inventing custom actions in URLs, REST uses standard HTTP methods to describe what you want to do with these resources.

Resources and Endpoints

A REST API groups related data into collections and individual items. Think of it as a set of nouns, not verbs.

A typical structure looks like this:

/users for all users
/users/{id} for a specific user
/posts for all posts
/posts/{id} for a specific post

The path usually represents:

Collection: /resource
Single item: /resource/{id}

Sometimes APIs nest resources to show relationships, for example /users/42/posts for all posts of user 42.

From an Android perspective, your app builds these URLs dynamically, for example by inserting IDs or query parameters, then sends requests to them.

HTTP Methods in REST

REST uses HTTP methods to express actions on resources. The most common methods you use from Android are GET, POST, PUT, PATCH, and DELETE.

GET retrieves data without changing anything on the server. For example, GET /users fetches a list of users, and GET /users/42 fetches user 42. In Android, simple data loading such as showing a list or details usually uses GET.

POST creates a new resource. For example, POST /users with a JSON body containing user data creates a new user. When your app sends forms, creates new posts, or uploads data, it often uses POST. The server usually returns the created resource, sometimes with a Location header telling you the URL of the new resource.

PUT updates a resource by replacing it with the body you send. For example, PUT /users/42 replaces user 42 with the new representation you provide. Some APIs use PUT when you send the full updated object.

PATCH updates part of a resource. For example, PATCH /users/42 can change only the email field. Many modern APIs prefer PATCH for partial updates, because you do not need to send all fields.

DELETE removes a resource. For example, DELETE /users/42 deletes user 42. In Android, this is used for actions such as removing items or canceling objects on the server.

Some REST APIs also use less common methods like HEAD or OPTIONS, but for most app features you work mainly with the five methods above.

Important rule:
In REST, you work with nouns (resources) and use HTTP methods (GET, POST, PUT, PATCH, DELETE) to describe actions on those resources.

REST and HTTP Status Codes

In a REST API, the server uses HTTP status codes to tell your app the result of a request. Correct handling of these codes is essential for a robust Android app.

A successful read request usually returns 200 OK. For example, GET /users that returns a list of users. Some successful operations use more specific codes. When you create something with POST the server often returns 201 Created. When you delete something and there is no content to return it might send 204 No Content.

When something is wrong with your request you see a 4xx status code. Common ones are 400 Bad Request when the input is invalid, 401 Unauthorized when authentication is missing or invalid, and 403 Forbidden when the user is not allowed to perform the operation. 404 Not Found appears when the resource does not exist.

Server side problems are reported with 5xx codes. For example, 500 Internal Server Error or 503 Service Unavailable. Your Android app should not treat these as user mistakes, but as temporary or server issues and maybe ask users to retry later.

Even when a request fails the response body often contains useful JSON with an error message or error code you can show in the UI.

Request URLs, Query Parameters, and Headers

A full REST request URL consists of the scheme, host, optional port, path, and optional query parameters. For example:

https://api.example.com/users?page=2&limit=20

The base part https://api.example.com is the common root for all endpoints of an API. Your Android app typically stores this base URL in a central place. You then append endpoint paths like /users and optional query parameters like ?page=2&limit=20 for pagination or filtering.

Query parameters are key value pairs that modify the request without changing the resource path. For example, GET /users?search=john might filter users by name, or GET /posts?sort=latest might change the sorting.

Headers carry metadata about the request. Common REST headers used from Android include Content-Type which usually is application/json for JSON bodies, Accept which tells the server what response format you want, and Authorization which carries tokens or keys for authenticated requests.

Your networking code will set headers and query parameters depending on what the API expects. These details are documented in the backend API specification.

Request Bodies and JSON Payloads

For REST endpoints that create or update data, the body of the HTTP request usually contains a JSON representation of the resource. For example, a POST to create a user might look like this:

POST /users
Content-Type: application/json
{
  "name": "Alice",
  "email": "alice@example.com"
}

In Android, you construct these JSON bodies from Kotlin objects, either manually or by using a JSON library to serialize them. You must match the field names and structure that the API expects.

Similarly, when the server responds it usually sends JSON too. For example, GET /users/42 might return:

{
  "id": 42,
  "name": "Alice",
  "email": "alice@example.com"
}

Your Android app parses this JSON into Kotlin data classes so that you can use the data comfortably in your UI and logic.

Statelessness and Client Responsibility

REST APIs are usually stateless. That means each request from your app must contain all the information the server needs to handle it. The server does not remember previous requests in a way that changes how it processes the next one for that client.

For Android apps this has some clear consequences. Authentication is often sent with every request, for example with Authorization: Bearer <token> headers. The server does not assume that you are logged in just because you authenticated once before. If you have a session token or access token you store it locally in the app and attach it to each relevant REST call.

Statelessness simplifies scaling on the server side and makes your app more predictable. If a network call fails, you can try again without worrying about hidden server session state, as long as you consider idempotency.

Idempotent and Non Idempotent Requests

In REST, some methods are considered idempotent. A request is idempotent if performing it once has the same effect as performing it multiple times.

GET, PUT, and DELETE are usually idempotent. Calling GET /users/42 several times does not change anything. Calling PUT /users/42 with the same body multiple times keeps the resource in the same state after the first call. Similarly, if DELETE /users/42 deletes the user, sending the same delete again typically has no further effect, although the response can differ.

POST is generally non idempotent. Sending the same POST to create a resource multiple times usually creates multiple resources. PATCH can be idempotent or not, depending on how the API is designed.

For Android apps this matters when you implement retries. You can usually retry idempotent requests safely. For non idempotent operations such as POST that create orders or payments you must be more careful, to avoid duplicate actions when the user taps a button multiple times or when the network is unstable.

Important statement:
Only retry non idempotent operations like POST with careful checks, to avoid creating duplicate data or actions on the server.

Versioning REST APIs

Servers do not stay the same forever, they evolve. To avoid breaking existing apps, many REST APIs use versioning. The version is often visible either in the URL or in headers.

A common pattern in URLs is something like https://api.example.com/v1/users and later https://api.example.com/v2/users. In this case your Android app selects a version by using the correct base URL or path prefix. Another pattern uses headers, for example a Accept header that includes a custom version.

Versioning affects how you define your data models and URLs. When an API introduces a new version, you might need to adjust your app to that version, or you might keep using the old one until you are ready to migrate.

Authentication and REST Endpoints

While the details belong to more specific security topics, REST APIs commonly restrict access through authentication tied to requests. Since REST APIs are stateless you include credentials or tokens every time.

A REST endpoint can require an API key in a header or query parameter, a bearer token in the Authorization header, or other mechanisms. The server then enforces which users can access which resources by checking these values before performing the requested action.

For your Android app this means that calls to protected endpoints will fail with 401 Unauthorized or 403 Forbidden if the token is missing, expired, or does not have the correct permissions. You need to listen to these status codes and trigger login flows or token refresh when necessary.

Consistency of REST Design

Many APIs claim to be RESTful but differ in how strictly they follow REST ideas. Some use verbs in URLs like /createUser instead of /users with POST. Some use POST for updates instead of PUT or PATCH.

As an Android developer, your main task is to adapt to the actual API design you integrate with. Still, understanding REST principles helps you read API documentation more easily, communicate clearly with backend developers, and design cleaner APIs if you ever help shape them.

REST encourages the use of consistent patterns. Similar resources should use similar endpoints and methods, JSON bodies should have predictable field names, and status codes should reflect the real outcome. When you see these patterns you can often guess how to interact with new endpoints even before reading all the details.

How REST Fits into Android Networking

In this chapter you focused on what REST is and how it uses HTTP for working with resources. For Android apps this provides a predictable structure for all network interactions: you know which HTTP method to choose, where to put data, how to interpret status codes, and how to handle JSON payloads.

Later, when you learn about specific networking libraries such as Retrofit, you will apply these REST concepts in code by defining interfaces and data models that map cleanly to the REST endpoints. Understanding REST first will make those tools feel much more natural.

Views: 2

Comments

Please login to add a comment.

Don't have an account? Register now!