Sub topic 1
How REST and HTTP work
Every request your Flutter app sends to a server is an HTTP exchange. If you can read that exchange, you can debug most networking problems without guessing. This chapter covers the vocabulary and rules that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you already know the following:
- Dart basics: classes, null safety and named parameters.
- Futures and
async/await. - Basic Flutter widgets and the
StatefulWidgetlifecycle. - How to add a package to
pubspec.yaml.
You do not need any networking background. The chapter has no Flutter UI code, so you can run its one example with plain dart run.
What HTTP is
HTTP (Hypertext Transfer Protocol) is a text-based request and response protocol. The client, here your app, opens a connection and sends one request. The server sends back one response. HTTP is stateless, so the server does not remember earlier requests unless you send something that identifies you, such as a token. Chapter 6 covers tokens.
HTTPS is HTTP carried inside an encrypted TLS connection. Use it for every real API. Plain http:// URLs are blocked by default on Android and iOS, as the next chapter explains.
What REST means
REST (Representational State Transfer) is a style for designing HTTP APIs. A REST API is built around resources, which are things the server manages, such as posts, users or orders. Each resource has a URL, and you act on it with an HTTP method.
- The URL names the thing:
/posts/1is post number 1. - The method says what to do with it: read, create, replace, change or remove.
- The body carries a representation of the resource, almost always JSON.
Many APIs that call themselves REST follow these rules only loosely. Always read the API's own documentation. Do not assume it follows convention.
Anatomy of a request
A request has four parts: a method, a URL, headers and an optional body. On the wire, a GET request looks like this:
GET /posts/1 HTTP/1.1
Host: jsonplaceholder.typicode.com
Accept: application/jsonThe first line holds the method, the path and the protocol version. The following lines are headers, which are Name: value pairs that describe the request. A GET request normally has no body.
A POST request that creates something carries a body, and headers that describe it:
POST /posts HTTP/1.1
Host: jsonplaceholder.typicode.com
Content-Type: application/json; charset=UTF-8
Content-Length: 18
{"title":"hello"}The URL
A URL breaks into parts that Dart's Uri class can build for you:
| Part | Example | Meaning |
|---|---|---|
| Scheme | `https` | Protocol and encryption |
| Host | `jsonplaceholder.typicode.com` | Which server |
| Port | `443` (implied) | Which port, 443 for HTTPS and 80 for HTTP |
| Path | `/posts/1` | Which resource |
| Query | `?userId=1` | Filters, sorting and paging |
Uri.https(host, path, queryParameters) assembles these parts and percent-encodes special characters in query values. Building URLs this way is safer than concatenating strings.
Methods
The method tells the server what you intend. Two properties matter for app code.
- A method is safe if it does not change server state.
- A method is idempotent if sending it several times has the same effect as sending it once.
| Method | Typical use | Safe | Idempotent |
|---|---|---|---|
| GET | Read a resource or a list | Yes | Yes |
| POST | Create a resource, or trigger an action | No | No |
| PUT | Replace a resource completely | No | Yes |
| PATCH | Change part of a resource | No | Not guaranteed |
| DELETE | Remove a resource | No | Yes |
Idempotency decides whether a failed request can be retried blindly. If a GET times out, sending it again is harmless. If a POST times out, the server may have created the record before the connection dropped, and a retry could create a duplicate. Chapter 8 returns to this.
Status codes
The response begins with a three-digit status code. The first digit gives the class.
| Range | Class | Examples |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301 Moved Permanently, 304 Not Modified |
| 4xx | Client error: your request is wrong | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Unprocessable Content, 429 Too Many Requests |
| 5xx | Server error: the server failed | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable |
Check the exact code, not only "did it work". A POST that creates a resource should answer 201, and a 200 may mean something different. A 204 has no body at all, so calling jsonDecode on it throws. A 401 means the server does not know who you are, and a 403 means it knows you but refuses. A 4xx response usually will not improve when retried unchanged. A 5xx or 429 sometimes will.
Headers and content types
Headers carry metadata. These are the ones you will meet most often:
Content-Typedescribes the format of the body you are sending, for exampleapplication/json.Accepttells the server which formats you can read.Authorizationcarries credentials, for exampleBearer <token>.Content-Lengthgives the body size in bytes.Retry-Afteron a 429 or 503 response says how long to wait.
Header names are case-insensitive. Dart's http package lowercases the keys of response.headers, so read response.headers['content-type'], not 'Content-Type'.
A missing or wrong Content-Type is a classic cause of failed POSTs. If you send a JSON string but declare nothing useful, many servers treat the body as form data or reject it with a 400 or 415.
JSON bodies
JSON (JavaScript Object Notation) is the usual body format. It has objects, arrays, strings, numbers, booleans and null. In Dart, jsonDecode turns JSON text into Map<String, dynamic>, List<dynamic> and primitive values. jsonEncode goes the other way.
{
"id": 1,
"title": "hello",
"tags": ["intro", "http"],
"author": null
}Because the decoded values are dynamic, a typo in a key or a wrong type fails only at runtime. Chapter 4 shows how model classes move those failures to one predictable place.
One full exchange
The diagram shows the path of a single GET from your app to the server and back.
Here is the same exchange as Dart code. It prints the three things you should look at first when a call misbehaves. Add http to your dependencies, for example with dart pub add http.
import 'package:http/http.dart' as http;
Future<void> main() async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/1');
final response = await http.get(
uri,
headers: {'Accept': 'application/json'},
);
print('Status: ${response.statusCode}');
print('Content-Type: ${response.headers['content-type']}');
print('Body: ${response.body}');
}Expect Status: 200, a content type that starts with application/json, and a JSON object body. The next chapters turn this sketch into production-quality code.
Common errors at this level
- Treating a non-2xx status as an exception. The
httppackage completes normally for a 404 or 500. It throws only when no response arrives at all, such as a lost connection. You must checkstatusCodeyourself. - Decoding before checking. Error responses are often HTML or an error JSON with a different shape. Check the status first, then decode.
- Wrong text encoding.
response.bodyuses the charset fromContent-Type, and it can fall back to Latin-1 when none is given. For JSON,utf8.decode(response.bodyBytes)avoids garbled non-ASCII text. - Retrying non-idempotent calls. Blindly repeating a POST can create duplicates.
- Hard-coding query strings. Build URLs with
Uriso values are encoded correctly.
Where this fits
The next chapters build on this model in order. Platform permissions let requests leave the device. GET requests and JSON models read data, and the write methods change it. After that come headers and errors, then structure, UI, tests and Dio. Each of them applies the same pieces you saw here: a method, a URL, headers, a body and a status code.
Exercise
Your app sends POST /orders to create an order. The connection times out, and you cannot tell whether the server received the request. Why is it risky to retry automatically, and which method would be safer to retry?
Show answer
POST is not idempotent. The server may have created the order before the connection dropped, so a retry could create a second order. GET, PUT and DELETE are idempotent, so repeating them has the same effect as sending them once. A common fix is to make the POST safe with an idempotency key, if the API supports one, or to check whether the order exists before retrying.
Exercise
A server answers a request with status 404 and an HTML error page. What does the http package's get do, and what happens if you pass response.body straight to jsonDecode?
Show answer
get completes normally and returns a Response with statusCode 404, because the server did answer. Passing the HTML to jsonDecode throws a FormatException. You should check the status code first and handle non-2xx responses before decoding.
Exercise
Which header tells the server that your request body is JSON, and which header tells it what format you want in the reply?
Show answer
Content-Type: application/json describes the body you send. Accept: application/json states the format you want back.