Making GET, POST, PUT, PATCH, and DELETE requests
This article tells how to make HTTP requests using the http package by the Dart team. We will be using JSONPlaceholder as a target for our API examples below. Thanks to this post for the idea.
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
I’ll demonstrate these with a simple app. You can find the code at the end of the article.
Setup
Add the http package dependency in pubspec.yaml.
dependencies:
http: ^0.13.3
Then add the following import at the top of the file where you’ll be making the HTTP requests:
import 'package:http/http.dart';
For the methods below, I’ll use the following URL prefix:
static const urlPrefix = 'https://jsonplaceholder.typicode.com';
GET requests
A GET request is used to get some resource from a server.
Future<void> makeGetRequest() async {
final url = Uri.parse('$urlPrefix/posts');
Response response = await get(url);
print('Status code: ${response.statusCode}');
print('Headers: ${response.headers}');
print('Body: ${response.body}');
}
The get
method above is part of the http library and makes the actual request. The response
that you get back contains the information you need.
Now replace /posts
with /posts/1
in the url
. Using /posts
returns an array of JSON objects while /posts/1
returns a single JSON object, where 1
is the ID of the post you want to get.
You can use dart:convert to convert the raw JSON string to objects. See Parsing Simple JSON in Flutter and Dart for help with that.
POST request
A POST request is used to create a new resource.
Future<void> makePostRequest() async {
final url = Uri.parse('$urlPrefix/posts');
final headers = {"Content-type": "application/json"}…