Skip to content
Dustin Catap edited this page Jun 19, 2024 · 2 revisions

API classes are one of the (remote) data sources of our application. It is used for REST API calls. Typically we cached the data from the API calls in the database. This is important if you plan to support offline functionality in your application.

The project uses retrofit to generate the code needed for the API classes.

Creating an API

// coverage:ignore-file

import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:retrofit/retrofit.dart';
import 'package:starterkit_app/core/data/api/dio_provider.dart';

part 'post_api.g.dart';

@lazySingleton
@RestApi()
abstract interface class PostApi {
  @factoryMethod
  factory PostApi(Dio dio) = _PostApi;

  @GET('/posts')
  Future<List<PostDataContract>> getPosts();

  @GET('/posts/{id}')
  Future<PostDataContract> getPost(@Path('id') int id);
}
  • We can annotate the methods according to the HTTP method they will perform (i.e. GET or POST).
  • @Path is used to specify the path parameter in the URL.
  • @lazySingleton is used to register the class in the dependency injection container as a single instance every time it is resolved.
  • A Dio instance is passed, with the necessary configurations for the API calls. This also sets the base URL for the API calls.

💡 TIP

  • Use the code snippet shortcut api to create an API class.