-
Notifications
You must be signed in to change notification settings - Fork 1
How it works
Now that our first example is up and running, let's understand what we've done. Lets take a look at the class below.
@API(path: 'beers')
class BeerAPI {
@GET()
List get() {
return ["Beer 1", "Beer 2"];
}
}
We define an API creating a pure Dart class and annotating it with the @API
annotation. It tells Darter it must look at this class carefully. In this case, Darter will examine this class looking for route handlers, error handlers, versioning strategies, and many other things. However, the first thing Darter will look for is the path
parameter. It's obligatory and in our example, it tells Darter to handle any request made to the URI http://yourdomain.com/beers
.
Once you have this class created and properly annotated with @API
, you can expose its methods. To achieve this goal, you must create public methods and annotate them with one of the following annotations: @GET
, @POST
, @PUT
, @DELETE
, and @PATCH
. In the example above, the method get
handles any GET request made to the endpoint http://yourdomain.com/beers
. Now, we'll add a new method to this class:
@GET(path: ':id')
String getById(Parameters pathParams) {
return "Beer ${pathParams['id']}";
}
This method is telling Darter it is responsible to handle any GET request to the URI http://yourdomain.com/<id>
, where <id>
can be anything. This <id>
is called path parameter and can be accessed through the Parameters
variable that has been passed to it. It's important to take into account that this parameter must be named exactly pathParams
. It's a convention and as you'll see Darter loves conventions.
@POST()
String post(Map object) {
return "Creating Beer ${object['id']} - {object['name']}";
}
The method above handles POST requests made to the URI http://yourdomain.com/beers
. The most important thing to take into account in this method is the Map
parameter. Darter will look into the request body and try to transform it into an instance of Map
. For example, if a JSON string has been provided in the body, Darter will decode this String and create a Map
based on this JSON object.
However, you're not limited to a Map
. It can even be your own object. Assume we have a class named Beer, as below:
class Beer {
String name;
int id;
}
Instead of using Map
as a parameter, you can use this class, as follows:
@POST()
String post(Beer beer) {
return "Creating Beer ${object['id']} - {beer.name}";
}
It's even possible to interpolate the path parameters with your own objects:
@PUT(path: ':id')
String update(Beer beer, Map pathParams) {
return "Updating Beer ${pathParams['id']} - {beer.name}";
}
Got it? Simple, right?