Summary - HTTP
- Dart course
- Advanced
- Lesson 36/83
- 5 min
Combine http.get, http.post and dio to write an API client.
Summary - HTTP
This group covered HTTP clients in Dart: the http package (get/post), Uri.parse, queryParameters, headers (content-type, authorization), dio (interceptor + auto JSON).
Core: GET reads data (no body), POST carries a body (content-type required for JSON). Uri.parse splits a URL into structural parts.
dio is preferred in larger projects; it offers an interceptor chain and automatic JSON parsing.
Practice Summary: URL + headers
Inside main add var u = Uri.parse('https://api.example.com/users');. Add var headers = {'content-type': 'application/json'};. Add print(u.host); and print(headers.length);.
Starter code
void main() {
// parse URL; build headers Map; print host and length
}Sample solution
void main() {
var u = Uri.parse('https://api.example.com/users');
var headers = {'content-type': 'application/json'};
print(u.host);
print(headers.length);
}Expected output
api.example.com 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is required for a JSON POST?
- Stream
- Isolate
- Router
- content-type header Correct answer
Explanation: the content-type: application/json header is required.
2 Match the concepts
| Term | Meaning |
|---|---|
get(Uri) |
GET request |
post(url, body:) |
POST request |
Uri.parse |
URL parsing |
Dio |
Advanced client |
3 Build a Uri
var u = ____(scheme: 'https', host: 'api.example.com');
var u = Uri(scheme: 'https', host: 'api.example.com');
Explanation: the Uri constructor builds a URL structure.