čtvrtek 7. ledna 2016

Dart RPC: Create RESTful API in a couple of minutes

I am on the front-end mostly because I like to work with UI. But let's move on and try something new, a little bit of server-side...


In this blog post I show you how to create your RESTful server-side API in Dart really fast! :-)

How to start

There is a really nice library on pub called RPC. It is a light-weight package for creating RESTful server-side Dart APIs. And this library is everything we need.

Let's start with adding dependency into pubspec.yaml in our project:

dependencies:
  rpc: "^0.5.5"

And then call pub get to get the package into our project.
Now you can import it.

import 'package:rpc/rpc.dart';

Create API class

We need to create API class which wraps our API. It is a Dart class with special @ApiClass annotation from the RPC library. The annotation has one mandatory parameter - version where we provide a version for our API. For example v1. You can also optionally provide other parameters like name to be able to rename the API.

@ApiClass(version: 'v1')
class MyApi {
  // here will be contents of the class.
}

API methods

We want to be able to provide API methods like GET, POST, DELETE, etc. We put them in our already prepared API class with special annotation.

Methods can be put directly into our API class or API resources can be used.

Methods in API class

Here we create the GET all animals and POST animal method. Every API method has to have the @ApiMethod annotation with mandatory path parameter where we specify the path which is used for calling of our method. We can also specify the method parameter where we provide type of the method which will be used. If the method parameter is omitted, the GET is used.

@ApiClass(version: 'v1')
class MyApi {
  List _animals = [];

  @ApiMethod(path: 'animals')
  List<Animal> getAnimals() => _animals;

  @ApiMethod(path: 'animals', method: 'POST')
  Animal postAnimal(Animal animal) {
    _animals.add(animal);
    return animal;
  }
}

We are using List for saving of our animals in this example. And we provide two methods: getAnimals() which returns a list of all animals and postAnimal() which saves a new animal into our list. Easy. Of course we could extend our example API with other methods.

To have it working we also need to have our Animal class:

class Animal {
  int id;
  String name;
  int numberOfLegs;
}

API resources

Usually we want to divide our API into resources which wrap the particular API methods. We want to for example have one API resource for an Animal and one API resource for a Person. We can do this with the RPC library easily.

Create the resource class and move all the resource methods in it:

class AnimalResource {
  List _animals = [];

  @ApiMethod(path: 'animals')
  List<Animal> getAnimals() => _animals;

  @ApiMethod(path: 'animals', method: 'POST')
  Animal postAnimal(Animal animal) {
    _animals.add(animal);
    return animal;
  }
}

And then create the AnimalResource instance into our API class with @ApiResource annotation:

@ApiClass(version: 'v1')
class MyApi {
  @ApiResource()
  AnimalResource resource = new AnimalResource();
}

Test the API

To be able to use and test our API, we need to create the server script in bin/ folder. We need to create the ApiServer there, add it our API and create a new HttpServer which starts listening on 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}');
}

Then run the Dart script in bin/ which starts the server and explore the API methods. Our API is available on localhost:8080/myApi/v1. If we want to get a list of all animals, we call GET on localhost:8080/myApi/v1/animals. Or we can try the POST for the new animal on the same address localhost:8080/myApi/v1/animals.

Trying a POST method is more difficult because we need to either install a tool like curl or we can use some extension to Chrome (like Advanced REST client or Postman).

And that's all! Now you have a really simple Dart API created in a couple of minutes.

Where can I find more?

This library can do even more. You can find all information about this library on the official RPC's site on pub or on Github.

My server Code Lab

I was happy to be and talk at couple of DevFests last year, where I had also a Dart code lab. My code lab was about server-side and as you could guess, I used the RPC library :-) You can take a look at and try the code lab on my Github.

Happy coding!

Žádné komentáře:

Okomentovat