CodeBlanks Logo Icon CodeBlanks

http.post

Send data with http.post.

What is http.post?

http.post is a method used to send data to a server. You set the content type with headers and the data to send with body.

final response = await http.post(
  Uri.parse(url),
  headers: {'Content-Type': 'application/json'},
  body: '{"name": "Ayşe"}',
);

POST is usually used to create a new record.

headers and body

headers carries extra information about the request; for example Content-Type specifies the body format. body is the actual data to send.

await http.post(
  uri,
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({'name': 'Ayşe'}),
);

For JSON data, Content-Type must be application/json.

Practice Send data with http.post

Write an async method veriGonder. In the http.post call, give Uri.parse('https://api.example.com/kullanici'). Add the parameters headers: {'Content-Type': 'application/json'} and body: '{"isim": "Ayşe"}'. Then print 'gönderildi: ${response.statusCode}'. In main, await the method.

Starter code

main.dart
import 'package:http/http.dart' as http;

// veriGonder: async metot ekle

void main() async {
  // veriGonder'i çağır
}

Sample solution

main.dart
import 'package:http/http.dart' as http;

Future<void> veriGonder() async {
  final response = await http.post(
    Uri.parse('https://api.example.com/kullanici'),
    headers: {'Content-Type': 'application/json'},
    body: '{"isim": "Ayşe"}',
  );
  print('gönderildi: ${response.statusCode}');
}

void main() async {
  await veriGonder();
}

Expected output

gönderildi: 201

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which parameter do you use to give the data to send to http.post?

  • uri
  • body Correct answer
  • headers
  • method

Explanation: You give the data to send to http.post via the body parameter; headers specify the content type.

2 Add the headers parameter to http.post

Question
final response = await http.post(
  uri,
  ____: {'Content-Type': 'application/json'},
  body: '{"isim": "Ayşe"}',
);
Answer
final response = await http.post(
  uri,
  headers: {'Content-Type': 'application/json'},
  body: '{"isim": "Ayşe"}',
);

Explanation: http.post's headers parameter carries extra info such as content type; body is the data to send.

3 http.post parts

Term Meaning
http.post Data sending method
headers Extra info such as content type
body Actual data to send
Content-Type Header specifying body format

All lessons in Intermediate