Building RESTful Web APIs with Dart, Aqueduct, and PostgreSQL — Part 1
Tags: api, webdev, dart, sql
Published: 2018-05-05 18:18:16

---
title: Building RESTful Web APIs with Dart, Aqueduct, and PostgreSQL — Part 1
published: true
description: A series covering how to build RESTful Web APIs with Dart, Aqueduct and PostgreSQL
tags: api, webdev, dart, sql
series: Building RESTful Web APIs with Dart, Aqueduct, and PostgreSQL
---

![Featured image for Building RESTful Web APIs with Dart, Aqueduct and PostgreSQL](https://thepracticaldev.s3.amazonaws.com/i/dv19znif0x9wpvdcdt13.jpg)

---

_**PLEASE NOTE: As of Dart 2 the API for Aqueduct has changed, leading to breaking changes. This article was based on Aqueduct 2.5.0 for Dart v1.**_

_**I have updated this as a new video series: [http://bit.ly/aqueduct-tutorial](http://bit.ly/aqueduct-tutorial)**_

---
 
In this new series on yet another RESTful API tutorial (#yetanotherrat), we will be exploring the Dart platform and its offering when it comes to building server-side applications.

Following on from [my last post](https://dev.to/graphicbeacon/learn-dart-before-you-flutter-2997) exploring the Dart language, I’d also been investigating how one might go about building RESTful services with Dart. Some further digging and I stumbled across Aqueduct by Stable Kernel. I was impressed at first glance seeing that it has already passed version 2 and once I figured the documentation was comprehensive with easy-to-follow examples, I was convinced to explore further.

Upon the experience of such a productive and refreshing time going through its documentation and following their example, I am now pleased to be taking you on this journey with me to build a working api from start to finish!

Prefer a video? [Watch on Youtube](https://youtu.be/XBRyW5Nrcqs)

---

## So what's Aqueduct?

Well it’s an open-source framework for creating and deploying RESTful web apis on the server. It has a similar flavour to _Express_ and _Hapi_, even _.NET Web API_, offering a point of entry with a comprehensive list of features.

My favourite ones are:

1. Fluid, chainable **routing**. _A functional style to composing your routes and its handler methods_
2. A **CLI** tool. _This allows you to scaffold your next project by issuing commands_
3. **Multi-threading** out of the box. _Spins up multiple instances of your application via Dart's "isolates", scaling across all CPU cores on the server._
4. Has an inbuilt **ORM**. _A must-have if you work with relational databases! Also supports databse migration._
5. Has an **integrated testing** library. _Because you need to test all the things! Plays well with tools like TravisCI._

In the series we will be building an api for a personal reading list (_let’s call it **FaveReads**_ 📚), covering these topics:

* **Part 1: Setting up and running the example** _(we're here)_
* [Part 2: Implementing routing with CRUD operations](https://dev.to/graphicbeacon/building-restful-web-apis-with-dart-aqueduct-and-postgresqlpart-2-routing-53ip)
* [Part 3: Connecting Web APIs to SQL database](https://dev.to/graphicbeacon/building-restful-web-apis-with-dart-aqueduct-and-postgresqlpart-3-postgres-9c7)
* [Part 4: Writing automated tests](https://dev.to/graphicbeacon/building-restful-web-apis-with-dart-aqueduct-and-postgresqlpart-4-testing-3974)
* [**\*Bonus content\*** DB Migration and Model Relationships](https://dev.to/graphicbeacon/building-restful-web-apis-with-dart-aqueduct-and-postgresqlbonus-content-551g) 😄

![Shall we begin?](https://thepracticaldev.s3.amazonaws.com/i/sh243oz27767ygjannp5.gif)

## Setting up and running the example

If you haven’t already, I’d encourage you to [install the Dart SDK](https://www.dartlang.org/tools/sdk#install). It’s got instructions for Windows, Mac and Linux.

You can confirm you have Dart running by checking the terminal:

```bash
dart --version
```
Dart comes with a tool called **pub** to manage its packages. Let’s use this tool to install Aqueduct:

```bash
pub global activate aqueduct
```
This gives us access to the `aqueduct` executable. Change to your working directory and let us create our project:

```bash
aqueduct create fave_reads && cd fave_reads
```
You should now be in the `fave_reads` directory with all the project files. For now we'll focus on:

```
bin/
  main.dart
lib/
  fave_reads_sink.dart
pubspec.yaml
```
* **bin/main.dart** _creates our server and starts the app_
* **lib/fave_reads_sink.dart** _sets up your application with its configuration_
* **pubspec.yaml** _contains metadata about the project. Similar to having a package.json for Node.js development_

Let’s start the application using either commands below:

```bash
aqueduct serve # or `dart bin/main.dart`
```
And here we go:

![Aqueduct serve terminal](https://thepracticaldev.s3.amazonaws.com/i/fplcso11d8iadkfpq4yd.png)

We now have a server running at `http://localhost:8081` with `/example` being the only created route. Accessing `http://localhost:8081/example` will return the response below:

```json
{ "key": "value" }
```
At this point its worth mentioning that Aqueduct has the concept of a RequestSink, which according to the documentation:

> _handles the initialization of an application, including setting up routes, authorization and database connections._

An application needs one `RequestSink` subclass to enable it to receive requests. Our example has a `FaveReadsSink` extending the base `RequestSink` class to enable us to override its methods with our own implementation. These are `setupRouter` and `willOpen`. The first method will allow us to define our routes with associated controllers and other middleware, while the latter allows us to perform any asynchronous initialisation after the routes are set up and before the application can receive requests.

The default response type is set to JSON for current requests. However this can be set to whatever content type is appropriate to meet our needs.

Let’s demonstrate this by creating a second route in setupRouter method:

```dart
router.route('/').listen((request) async {
  return new Response.ok('Hello world')
    ..contentType = ContentType.TEXT;
});
```
Using method cascades, we are able to set the `contentType` property to `text/plain`. The `ContentType` utility comes [inbuilt](https://api.dartlang.org/stable/1.24.3/dart-io/ContentType-class.html) with Dart and can be used through the style below:

```dart
new ContentType(primaryType, subType, {String charset, Map parameters});
```
It’s already got constants for HTML, JSON and TEXT so in most scenarios you should just use those.

Now restart the server by killing the current process and running `aqueduct serve` again. Accessing the root path should now give you this:

![Aqueduct server localhost](https://thepracticaldev.s3.amazonaws.com/i/pyetxyk5nm91dbtjzcnq.png)

Before we wrap up, lets scale up our application instances to the number of cores we have. In **bin/main.dart** it is currently set to 2 when app.start is invoked:

```dart
await app.start(numberOfInstances: 2);
```
To resolve this, we will import Dart’s [Platform](https://api.dartlang.org/stable/1.24.3/dart-io/Platform-class.html) class from the “dart:io” library and amend **main.dart** as follows:

```dart
import 'dart:io' show Platform;

Future main() async {
  ...
  ...
  await app.start(numberOfInstances: Platform.numberOfProcessors);
  ...
}
```
## Some development tips for VS Code 👈

Firstly, make sure to install the [Dart](https://marketplace.visualstudio.com/items?itemName=Dart-Code.dart-code) extension by Dart Code, to enable Dart and Flutter support.

Secondly, add a launch configuration for Dart with this setting:

```json
{
  "name": "Dart",
  "type": "dart",
  "request": "launch",
  "program": "${workspaceFolder}/bin/main.dart"
}
```
This will allow you to run the app through VS Code with the ability to add breakpoints to help with debugging.

![VS Code debugging with Dart](https://thepracticaldev.s3.amazonaws.com/i/2434ol0dmaafrj1y74qn.gif)

---

Before we wrap up, I want to ask you something…**What do you expect to gain at the end of this series?** Add a comment below to let me know, thanks.

And this concludes Part 1 of the series. The code for this series is [available on github](https://github.com/graphicbeacon/favereads) and will be updated as we go through the series. Stay tuned for more.

## Further reading

1. [Aqueduct documentation](https://aqueduct.io/docs)
2. [Getting started with Pub](https://www.dartlang.org/tools/pub/get-started)
3. [Presentation by Joe Conway at Dart Developer Summit 2016](https://www.youtube.com/watch?v=twr3cDFCeo4)

---

{% link https://dev.to/graphicbeacon/building-restful-web-apis-with-dart-aqueduct-and-postgresqlpart-2-routing-53ip %}

---

_Originally posted on [Medium](https://itnext.io/building-restful-web-apis-with-dart-aqueduct-and-postgresql-3cc9b931f777)_