Sub topic 5
Creating, updating and deleting resources
This chapter assumes you can make a GET request with the http package, decode JSON into a model class, and read a status code. It also assumes you are comfortable with async/await and named parameters. Here you will cover the four methods that change data on a server: POST, PUT, PATCH and DELETE.
What each method means
A REST API treats data as resources, each with its own URL. The HTTP method tells the server what you want to do with that resource.
| Method | Typical use | Body | Usual success status | Idempotent |
|---|---|---|---|---|
| POST | Create a new resource in a collection | Yes | 201 Created | No |
| PUT | Replace a resource completely | Yes | 200 OK or 204 No Content | Yes |
| PATCH | Change some fields of a resource | Yes | 200 OK or 204 No Content | Usually |
| DELETE | Remove a resource | Normally none | 200 OK or 204 No Content | Yes |
An operation is idempotent when repeating it leaves the server in the same state as running it once. This matters later, when you decide whether a failed request is safe to retry. Sending the same POST twice can create two resources. Sending the same DELETE twice leaves the resource deleted both times, although the second response is often 404 Not Found.
These are conventions, not rules enforced by the protocol. Always check the API's documentation for the exact statuses it returns. The examples in this chapter use jsonplaceholder.typicode.com, a free fake API. It accepts writes and returns realistic responses, but it does not save anything.
Creating a resource with POST
A POST request carries a body. With a JSON API, you do two things: encode the Dart data with jsonEncode, and declare the format in the Content-Type header.
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
Map<String, dynamic> toJson() => {'id': id, 'title': title};
}
Future<Post> createPost(http.Client client, String title) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts');
final response = await client.post(
uri,
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode({'title': title}),
);
if (response.statusCode != 201) {
throw Exception('Failed to create post: ${response.statusCode}');
}
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}Three details are worth noting.
- The client sends only
title. The server assigns theid, so the response is the only place you learn it. Return the decoded response, not the object you sent. - The success check is
201, not200. A server that creates something should answer 201 Created, often with aLocationheader pointing at the new resource. - The
bodyparameter accepts aString, aList<int>of bytes, or aMap<String, String>. With a map, the package sends form-encoded data (application/x-www-form-urlencoded) and ignores your JSON content type. Passing aMapto a JSON API is a very common mistake. The server then receivestitle=helloinstead of{"title":"hello"}and usually answers 400 or 415.
Why the Content-Type header matters
When you pass a String body and no Content-Type, the http package sends text/plain; charset=utf-8. Many servers then refuse to parse the body as JSON, or parse it as empty. Setting application/json tells the server which parser to use. The charset=UTF-8 part is optional for JSON, which is UTF-8 by definition, but harmless.
The same issue affects responses. In http, response.body decodes bytes using the charset in the response's Content-Type header. If the server omits the charset, the package falls back to Latin-1, and non-ASCII text such as accented letters can come out garbled. If you see broken characters, decode the bytes yourself:
import 'dart:convert';
import 'package:http/http.dart' as http;
Object? decodeUtf8Json(http.Response response) =>
jsonDecode(utf8.decode(response.bodyBytes));Replacing a resource with PUT
PUT sends the complete new representation of a resource to its own URL. Anything you leave out may be reset or removed on the server, depending on the API. Use PUT when your app holds the full object, for example after the user edits every field in a form.
Future<Post> updatePost(http.Client client, Post post) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/${post.id}');
final response = await client.put(
uri,
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(post.toJson()),
);
if (response.statusCode != 200) {
throw Exception('Failed to update post: ${response.statusCode}');
}
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}The URL identifies the resource, so the id appears in the path. Many APIs also include it in the body. Because PUT is idempotent, sending this request twice is safe and leaves the same result.
Changing some fields with PATCH
PATCH sends only what changes. It is the better fit when the user edits one field, or when the full object is large.
Future<Post> renamePost(http.Client client, int id, String title) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/$id');
final response = await client.patch(
uri,
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode({'title': title}),
);
if (response.statusCode != 200) {
throw Exception('Failed to rename post: ${response.statusCode}');
}
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}Servers differ in how they read a PATCH body. Most use a simple "merge these fields" style. Some expect JSON Patch (application/json-patch+json) with a list of operations, or JSON Merge Patch (application/merge-patch+json), where null means "remove this field". Check which one your API uses. If you send {"nickname": null} to a merge-patch server, you delete the nickname, which is different from leaving it out.
The Post model above has only two fields, so the PATCH response might not include everything. If your fromJson casts a missing key with as String, a partial response throws a TypeError. Some APIs answer a PATCH with 204 and no body, in which case there is nothing to decode.
Removing a resource with DELETE
Future<void> deletePost(http.Client client, int id) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/$id');
final response = await client.delete(uri);
final ok = response.statusCode == 200 || response.statusCode == 204;
if (!ok) {
throw Exception('Failed to delete post: ${response.statusCode}');
}
}Here the function returns Future<void> because a successful delete has nothing useful to return. Do not call jsonDecode(response.body) on a 204 response. The body is empty, and decoding an empty string throws a FormatException.
A 404 on DELETE deserves a decision. If the user's goal is "this item should not exist", a 404 means the goal is already met. You may choose to treat it as success. If you do, make that choice explicit instead of letting it slip through a generic status check.
Accepting a range of success codes
Hard-coding one status per call is brittle. A server might change 200 to 204, or an API gateway might answer with 202 Accepted. A small helper keeps the check in one place:
bool isSuccess(http.Response response) =>
response.statusCode >= 200 && response.statusCode < 300;Combine it with an empty-body check when decoding:
Post? decodePostOrNull(http.Response response) {
if (response.body.isEmpty) return null;
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}The nullable return makes the "no content" case visible to callers. The next chapters build a fuller error model; for now the rule is: check the status first, then decode only if there is a body.
How the request flows
The sequence below shows a create followed by a delete, including the point where the server assigns the id.
Common mistakes
- Sending a
Mapas the body. This produces form encoding. UsejsonEncode. - Forgetting
Content-Type. The server may ignore or reject the body. - Expecting the fake API to persist data. JSONPlaceholder returns
id: 101for every POST, and a later GET for that id returns 404. This is by design. - Decoding an empty body. A 204 response has no body. Check before calling
jsonDecode. - Using PUT for a partial change. Fields you omit may be wiped. Use PATCH, or send the full object.
- Retrying a POST blindly. After a timeout you do not know if the server created the resource. A blind retry can create a duplicate. Some APIs accept an
Idempotency-Keyheader to make this safe. Timeouts and retries are covered in a later chapter. - Not closing the client. If you create an
http.Client, callclose()when finished. Creating one client and reusing it is cheaper than creating one per call, because it can keep connections open.
Putting it together
This short program creates a post, renames it, and deletes it. Against JSONPlaceholder each call succeeds, though nothing is stored.
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
Map<String, dynamic> toJson() => {'id': id, 'title': title};
}
const _headers = {'Content-Type': 'application/json; charset=UTF-8'};
Future<void> main() async {
final client = http.Client();
try {
final created = await client.post(
Uri.https('jsonplaceholder.typicode.com', '/posts'),
headers: _headers,
body: jsonEncode({'title': 'hello'}),
);
final post =
Post.fromJson(jsonDecode(created.body) as Map<String, dynamic>);
print('Created id ${post.id} (status ${created.statusCode})');
final patched = await client.patch(
Uri.https('jsonplaceholder.typicode.com', '/posts/1'),
headers: _headers,
body: jsonEncode({'title': 'renamed'}),
);
print('Patched status ${patched.statusCode}');
final deleted = await client.delete(
Uri.https('jsonplaceholder.typicode.com', '/posts/1'),
);
print('Deleted status ${deleted.statusCode}');
} finally {
client.close();
}
}The try/finally block guarantees the client is closed even if a request throws. The patch and delete target /posts/1 because the fake API holds no record for the new id 101.
Exercise
A teammate writes client.post(uri, headers: {'Content-Type': 'application/json'}, body: {'title': 'hello'}). The server answers 400. What is wrong, and how do you fix it?
Show answer
Passing a Map as body makes the package send form-encoded data (title=hello) and ignore the JSON content type. Wrap the map in jsonEncode, so the body is the string {"title":"hello"}, which matches the declared application/json header.
Exercise
A user edits only the title of a post that has ten fields. Which method should you use, and what two precautions apply to the response?
Show answer
Use PATCH and send only {"title": ...}. Do not assume the response contains every field, so make fromJson tolerate missing keys or fetch the full resource again. Also do not call jsonDecode if the server answers 204 with an empty body.
Exercise
A POST to create an order times out. Why is it unsafe to simply send it again, and what can an API offer to make a retry safe?
Show answer
POST is not idempotent, and a timeout does not tell you whether the server already processed the request. A second request may create a duplicate order. An API can accept an Idempotency-Key header, so the server recognizes the repeat and returns the original result instead of creating a second order.