Back to Home

Create a RESTful API with Dart in minutes

dart · rest · restful api · server-side

Create a RESTful API with Dart in minutes

Original author: Jana Moudrá
  • Transfer
  • Tutorial


Translator's note: I would like to give readers one more reason to look at the wonderful Dart programming language, this time we will talk about how to quickly and easily create a RESTful API. For those who are not in the know, this is clearly described what it is.
And for those who are in the know, welcome to cat.

Where to begin


The pub has a great library called RPC. This is a lightweight package for building a server-side RESTful API on Dart. And that’s all we need.

Let's start by adding a dependency to our project in pubspec.yaml:

dependencies:
  rpc: "^0.5.5"

Then call pub get to load the packages into our project.
Now you can import.

import 'package:rpc/rpc.dart';


Create an API Class


We need to create an API class that will contain our API. This is a Dart class with a special @ApiClass annotation from the RPC library. An annotation has one required parameter - version, which means the version of the API provided. For example v1. You can also add other parameters, such as a name, to be able to rename the API.

@ApiClass(version: 'v1')
class MyApi {
  // Здесь будет содержимое класса
}

API Methods


We want to provide the ability to do GET, POST, DELETE, etc. inquiries. We all put them an API class with special annotation. Methods can be placed directly in the API class, or you can use API resources.

Classroom methods


Here we create the GET methods for animals and the POST methods for animal. Each method must have an @ApiMethod annotation with the required path parameter, which indicates the path to call our method. You can also specify a parameter that will indicate the type of method (GET, POST, etc.). If this parameter is not specified, then GET is set by default.

@ApiClass(version: 'v1')
class MyApi {
  List _animals = [];
  @ApiMethod(path: 'animals')
  List getAnimals() => _animals;
  @ApiMethod(path: 'animals', method: 'POST')
  Animal postAnimal(Animal animal) {
    _animals.add(animal);
    return animal;
  }
}

Here we use List to store animals. And we provide two methods: getAnimals (), which returns a list of all animals and postAnimal, which adds a new animal entry to the animals list. Naturally, we can extend this example with other API methods.

For this to work, we need the Animal class:
class Animal {
  int id;
  String name;
  int numberOfLegs;
}

API Resources


Usually we want to split our API into resources that provide specific API methods. For example, we want to have one resource for the API for Animals and one for Person. Using the RPC library, we can do this easily.

We create a resource class and move there all methods associated with the resource:
class AnimalResource {
  List _animals = [];
  @ApiMethod(path: 'animals')
  List getAnimals() => _animals;
  @ApiMethod(path: 'animals', method: 'POST')
  Animal postAnimal(Animal animal) {
    _animals.add(animal);
    return animal;
  }
}

Then we create an instance of AnimalResource in our API class, on which there is an @ApiResource annotation:
@ApiClass(version: 'v1')
class MyApi {
  @ApiResource()
  AnimalResource resource = new AnimalResource();
}

Testing API


To use or test our API, we need to create a server script in the bin folder. We need to create ApiServer here, add our API there and create an HttpServer that will listen to localhost: 8080.
library my_server;
import 'dart:io';
import 'package:logging/logging.dart';
import 'package:rpc/rpc.dart';
import '../lib/server/api.dart';
final ApiServer apiServer = new ApiServer(prettyPrint: true);
main() async {
  Logger.root..level = Level.INFO..onRecord.listen(print);
  apiServer.addApi(new MyApi());
  HttpServer server = await HttpServer.bind(InternetAddress.ANY_IP_V4, 8080);
  server.listen(apiServer.httpRequestHandler);
  print('Server listening on http://${server.address.host}: ${server.port}');
}

Now run the Dart script in bin which starts the server. Now our API is available at localhost: 8080 / myApi / v1. If we want to get a list of animals, we create a GET request for localhost: 8080 / myApi / v1 / animals. Or we can add a record by making a POST request to the same localhost address: 8080 / myApi / v1 / animals.

Testing a POST request is a bit more difficult, because To do this, install a tool such as curl or an extension for Chrome Postman or Advanced REST client.

That's it, the server API was created in just a few minutes.

Read Next