Serverless API Service with Webtask.io for Android

Nsikak Thompson
DroidPlate
Published in
5 min readFeb 22, 2018

--

The Serverless Framework helps you develop and deploy serverless applications.

Introducing Auth0 Webtasks. The Serverless CLI offers structure, automation and best practices out-of-the-box. And with Auth0 Webtasks it’s simple and easy to deploy code in just seconds.

In this article we will be build a simple article-api service for our Android App. The Article App will be feeding from the api based on webtask.io. This api will be used to perform basic CRUD task with the following HTTP methods . POST, GET, PUT, DELETE.

Article fields

  • Title
  • Author
  • Content
  • ThumbUrl

Getting Started with Webtask.io

Webtasks is a simple, lightweight, and secure way of running isolated backend code that removed or reduces the need for a backend.

Webtask is owned by Auth0 an internally key element of their identity management platform. You can play with the service and read more about it here,

Setup

Firstly your need to install the command line tool with the following command. This will get all you need set.

$ npm i -g wt-cli $ wt init

To test if it working. Create hello.js file and add this functions

module.exports = function (done) { done(null, ‘Hello!’); }

The simply create a function on the webtask server that returns Hello! when the function is triggered. Just run

$ wt create hello.js

This will return a URL on your terminal . Test the URL with your browser any console of your choice.

Test results

Coooooool!!! You Deserve some accolades …

Now that we have made it work. Let get into creating the Full Article API

API Structure

Package.json -> this contains all the project dependencies that will be needed to get our project ready for Webtask.io.

{"name": "article-api","version": "1.0.0","description": "Article tes api","main": "index.js","scripts": {"start": "npm run create -- --watch","create": "wt create index --bundle"},"author": "","license": "MIT","dependencies": {"body-parser": "^1.18.2","express": "^4.15.2","mongoose": "^4.9.5","webtask-tools": "^3.2.0"}}

Webtask Programming & Express

An app is simply created on webtask by exporting a function and an app is created.

Webtask has a utility tool, webtask-tools, to help you bind your express app to a Webtask context. Therefore, rather than exporting a simple function, you can export an express app bound to Webtask using webtask-tools:

body-parser parse incoming request bodies in a middleware before your handlers, available under the req.body property.

var Express = require('express');var Webtask = require('webtask-tools');var bodyParser = require('body-parser');var app = Express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
//database connection/disconnection and routesapp.use(require('./middleware/db').connectDisconnect);require('./route/articles')(app);module.exports = Webtask.fromExpress(app);

Database & Connections

Mongolab Database

Mongolab by Object Labs is a good choice for cloud database because they eliminate the challenges of knowing how to setup a Cloud DB by just giving you a URL after choosing where you want your database to be hosted. To get started:

  • Quickly Sign up.
  • Create a database. (Take note of the Database url)
  • Create a user to authenticate the database. You can do this by clicking on the just created database, selecting the Users’ tab and clicking Add database user.

Creating Mongoose Schema

Mongoose is a JavaScript framework that is commonly used in a Node.js application with a MongoDB database. It will create an interface for performing CRUD functions.

const mongoose = require('mongoose');module.exports = new mongoose.Schema({author: String,content: String,title: String,imageurl: String,created_at: Date,id: mongoose.Schema.ObjectId})

Db Connection

At this point we need a middleware to connect and disconnect the database a certain point.

This middleware handles both connecting and disconnecting to a Mongolab database. The connection is achieved by passing a connection URL(req.webtaskContext.secrets.MONGO_URL) to the createConnection method

var mongoose = require('mongoose');// import Story schemaconst ArticleSchema = require('../models/Article')module.exports = {// Connect/Disconnect middlewareconnectDisconnect: (req, res, next) => {// Create connection using Mongo Lab URL// available in Webtask contextconst connection = mongoose.createConnection(req.webtaskContext.secrets.MONGO_URL);// Create a mongoose model using the Schemareq.articleModel = connection.model('Article', ArticleSchema);req.on('end', () => {// Disconnect when request// processing is completedmongoose.connection.close();})// Call next to move to// the next Express middlewarenext()},}

The Connection url will be created from your terminal before deploying your functions.

Express CRUD Routes

We will be creating the various route to help handle all the API request.

var mongoose = require('mongoose');const Article = require('../models/Article');//Webtask funtionsmodule.exports = (app) => {//fetch all the articles from the db using a GETapp.get('/articles', (req, res) => {req.articleModel.find({}).sort({'created_at': -1}).exec((err, articles) => res.json(articles))});//Create new Article using a POSTapp.post('/articles', (req, res) => {const newArticle = new req.articleModel(Object.assign({}, req.body, {created_at: Date.now()}));newArticle.save((err, savedArticle) => {res.json(savedArticle)res.json(req.body)})})//Update articles from the db with {id} using PUTapp.put('/articles', (req, res) => {const idParam = req.webtaskContext.query.id;req.articleModel.findOne({_id: idParam}, (err, storyToUpdate) => {const updatedArticle = Object.assign(articleToUpdate, req.body);updatedArticle.save((err, article) => res.json(article))})})//Delete an articles from the db with {id} DELETE
app.delete('/articles', (req, res) => {
const idParam = req.webtaskContext.query.id;req.articleModel.remove({_id: idParam}, (err, removedArticle) => res.json(removedArticle));})}
  • GET: /articles route uses mongoose to fetch all the articles stored in the database and sort them by date created in descending order
  • POST: /articles is used to create a new article
  • PUT: /articles gets an id query string which it uses to find article and updates the article based on the id reference
  • DELETE: /articles PUT, expects an id as well and removes an entry from the database collection based on the id

Great

Deploying your App

We will now deploy our webtask functions. MONGOLAB-CONNECTION-URL should be replaced with your Mongolab DB URL.

wt create index --secret MONGO_URL=<MONGOLAB-CONNECTION-URL> --bundle

TEST your Webtask function with the return URL from your terminal. With POSTMAN or any other console of your choice.

https://wt-e681794554391ac97c69e1539e0c67df-0.run.webtask.io/article-api/articles

Articles returned from Postman

This API was actually consumed by Android using Retrofit Network Library. Hope this helped.

Webtask is actually a great serverless backend tool.

See full source code here

--

--

Nsikak Thompson
DroidPlate

Android developer | Technical writer | Community Enthusiast