Interacting with REST APIs

  • Interacting with REST APIs

Interacting with REST APIs

Interacting with REST APIs in Dart is typically done using the http package, which provides a simple and effective way to perform HTTP requests Here’s a step-by-step guide on how to set up and interact with a REST API in Dart:

Step 1: Add the http Package to Your Project

First, you need to add the http package to your pubspec.yaml file:Then, run dart pub get to install the package.

dependencies:
  http: ^0.14.0

Step 2: Import the http Package

Import the http package in your Dart file:

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

Step 3: Making HTTP Requests

You can use various methods provided by the http package to make different types of HTTP requests, such as GET, POST, PUT, DELETE, etc. Example: Making a GET Request

void main() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    print('Title: ${data['title']}');
  } else {
    print('Failed to load post');
  }
}

Example: Making a POST Request

void main() async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    headers: {'Content-Type': 'application/json; charset=UTF-8'},
    body: jsonEncode({
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    }),
  );

  if (response.statusCode == 201) {
    final data = jsonDecode(response.body);
    print('Created post: ${data['id']}');
  } else {
    print('Failed to create post');
  }
}

Step 4: Handling Errors

Handling errors is crucial when dealing with network requests. You should handle different types of errors, such as network failures, server errors, and unexpected responses.

Example: Handling Errors

void main() async {
  try {
    final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      print('Title: ${data['title']}');
    } else {
      print('Failed to load post, status code: ${response.statusCode}');
    }
  } catch (e) {
    print('Error occurred: $e');
  }
}

Step 5: Using Custom Headers

You can pass custom headers in your HTTP requests.

Example: Using Custom Headers

void main() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/posts/1'),
    headers: {
      'Authorization': 'Bearer your_api_token',
    },
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    print('Title: ${data['title']}');
  } else {
    print('Failed to load post');
  }
}

Step 6: Working with Query Parameters You can add query parameters to your requests.

Example: Using Query Parameters

void main() async {
  final uri = Uri.https('jsonplaceholder.typicode.com', '/posts', {'userId': '1'});
  final response = await http.get(uri);

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    print('Posts: $data');
  } else {
    print('Failed to load posts');
  }
}

Step 7: Parsing JSON Responses Use the dart:convert library to parse JSON responses.

Example: Parsing JSON Responses

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

void main() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));

  if (response.statusCode == 200) {
    final Map<String, dynamic> data = jsonDecode(response.body);
    print('Title: ${data['title']}');
  } else {
    print('Failed to load post');
  }
}