Creative Bracket

Build Web APIs with Aqueduct #3

In this article we will look at Serializable classes and how they enable us to handle the payload of a request body. We will then proceed to set up and integrate our PostgreSQL database.


What are Serializable objects?

These objects are responsible for encoding and decoding the payload of a request. To use one of these, extend the Serializable class and override the asMap() and readFromMap() methods.

class Read extends Serializable {
  String title;
  String author;
  int year;

  @override
  Map<String, dynamic> asMap() => {
    'title': title,
    'author': author,
    'year': year,
  }

  @override
  void readFromMap(Map<String, dynamic> requestBody) {
    title = requestBody['title'] as String;
    author = requestBody['author'] as String;
    year = requestBody['year'] as int;
  }
}

So the asMap() method takes in the instance members of Read and returns a Map structure, useful when returning JSON responses.

readFromMap() is used when extracting the request payload keys into our instance properties. This allows us to therefore bind our instance to the body payload parameter that comes in our POST request method:

class ReadsController extends ResourceController {
  ...
  ...
  @Operation.post()
  Future<Response> createNewRead(@Bind.body() Read body) async {
    // Notice the `body` parameter cast to the `Read` Serializable subclass
    ...
  }
  ...
  ...
}

See how this works in more detail and how we integrate a fully functional PostgreSQL database in the full video.

Continue watching

Further reading

  1. Handling HTTP Requests: Serializable Objects
  2. Aqueduct Docs: Reading from a Database
  3. Free Dart screencasts on Egghead.io

Sharing is caring 🤗

If you enjoyed reading this post, please share this through the various social buttons hovering on the left/top side of the screen ↖️⬆️. Also, check out and subscribe to my YouTube channel (hit the bell icon too) for videos on Dart.

Watch my Free Get started with Dart course on Egghead.io and Subscribe to my email newsletter to download my Free 35-page eBook titled Get started with Dart and to be notified when new content is released.

Like, share and follow me 😍 for more content on Dart.

Jermaine Oppong

Hello 👋, I show programmers how to build full-stack web applications with the Dart SDK. I am passionate about teaching others, having received tremendous support on sites like dev.to and medium.com for my articles covering various aspects of the Dart language and ecosystem.