#14 - API Service example in Dart

Date: 2018-06-23 12:00 - dart

Example of API service in Dart that could be used to easily call methods on an API.

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

final apiService = new APIService._private();

class APIService {
  static const baseURL = 'https://your.website.url/api/';
  APIService._private();

  post(String endpoint, {Object data}) async {
    final response = await http.post(baseURL + endpoint, body: json.encode(data));
    return json.decode(response.body);
  }

  get(String endpoint) async {
    final response = await http.get(baseURL + endpoint);
    return json.decode(response.body);
  }
}

Previous snippet | Next snippet