Sub topic 5
Creating, updating and deleting resources
This chapter assumes you know Dart classes, null safety, Future, async and await, and how to add the http package to a Flutter project. A REST API usually represents data as resources. For example, a /posts/1 resource can be created, replaced, partly changed, or deleted.
Match the operation to the HTTP method
HTTP methods communicate the intended operation:
| Method | Common purpose | Typical success status |
|---|---|---|
| `POST` | Create a new resource | `201 Created` |
| `PUT` | Replace a resource completely | `200 OK` or `204 No Content` |
| `PATCH` | Change selected fields | `200 OK` or `204 No Content` |
| `DELETE` | Remove a resource | `200 OK` or `204 No Content` |
A successful response does not always contain JSON. A 204 No Content response has an empty body, so attempting to decode it causes an error.
The following client sends JSON to JSONPlaceholder. The same structure works with your own API after changing the base URL and resource paths.
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) {
return Post(
id: json['id'] as int,
title: json['title'] as String,
);
}
final int id;
final String title;
Map<String, dynamic> toJson() {
return {'id': id, 'title': title};
}
}
class PostsApi {
PostsApi(this.client);
final http.Client client;
static const host = 'jsonplaceholder.typicode.com';
Future<Post> createPost(String title) async {
final response = await client.post(
Uri.https(host, '/posts'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode({'title': title}),
);
_checkStatus(response, expected: {201});
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
Future<Post> replacePost(Post post) async {
final response = await client.put(
Uri.https(host, '/posts/${post.id}'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(post.toJson()),
);
_checkStatus(response, expected: {200});
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
Future<Post> renamePost(int id, String title) async {
final response = await client.patch(
Uri.https(host, '/posts/$id'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode({'title': title}),
);
_checkStatus(response, expected: {200});
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
Future<void> deletePost(int id) async {
final response = await client.delete(Uri.https(host, '/posts/$id'));
_checkStatus(response, expected: {200, 204});
}
void _checkStatus(
http.Response response, {
required Set<int> expected,
}) {
if (!expected.contains(response.statusCode)) {
throw Exception(
'Request failed with status ${response.statusCode}',
);
}
}
}POST sends only the fields needed to create the resource. PUT sends the complete replacement. PATCH sends only the changed fields. The server decides whether omitted fields remain unchanged, receive defaults, or cause validation errors, so check the API documentation.
Validate responses before decoding
Check the status code before calling jsonDecode. Otherwise, an error page or an empty body can produce a misleading JSON parsing exception. Also validate required fields when the API can return incomplete or unexpected data.
When a create or update request succeeds, the server may return the stored representation, including a generated ID, timestamps, or normalized values. Use that returned object instead of assuming the local request exactly matches the server state.
Follow the resource lifecycle
Exercise
Which method should you use to change only a post's title, and why should you avoid decoding a 204 response?
Show answer
Use PATCH because it changes selected fields without replacing the complete resource. A 204 response has no body, so decoding it as JSON fails.