[go: up one dir, main page]

DEV Community

Cover image for Creating a serverless API and CLI tool
Paul Chin Jr.
Paul Chin Jr.

Posted on

Creating a serverless API and CLI tool

Have you ever wanted to have an image of Nicolas Cage directly from your terminal? In this post we will create an http endpoint that serves an image, and then we will build a CLI tool that accesses that endpoint.

Creating the API

Today we'll make a new http endpoint using Begin. To get started click the button below to create a hello world example.

Deploy to Begin

To login to Begin all you need is a GitHub account. Once logged in, give your new API a cool name. Begin will create a repo and set up your CI/CD at the same time. Now each time you push to main your changes get deployed to a staging environment.

When the repo is created, go ahead and clone it and open in your favorite text editor.

The first thing we'll change is index.js, change it to the following:

// index.js
exports.handler = async function http(req) {

  return {
    headers: {
      'content-type': 'text/html; charset=utf8',
      'cache-control': 'no-cache, no-store, must-revalidate, max-age=0, s-maxage=0'
    },
    statusCode: 200,
    body: JSON.stringify({ image: `${process.env.BEGIN_STATIC_ORIGIN}/1.jpeg`})
  }
}

Enter fullscreen mode Exit fullscreen mode

Next, we need to create a public folder in the root of our application and put an image in it to be served.

Now, we can push these changes and deploy the endpoint. Make note of the public url for your staging environment. We'll be making a GET request to it for the image from the CLI tool.

Creating the CLI tool

We'll create a new project called praise-cage-cli.

npm init -y
Enter fullscreen mode Exit fullscreen mode

Then go into your package.json and add a bin property. This bin property will give you a command to

{
  "name": "praise-cage-cli",
  "version": "1.0.2",
  "description": "",
  "main": "index.js",
  "bin": {
    "praise-cage": "cli.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "tiny-json-http": "^7.3.0",
  }
}
Enter fullscreen mode Exit fullscreen mode

Create a cli.js file in the root and npm install tiny-json-http as a dependency. We will be using tiny-json-http to fetch the image from our API.

cli.js should look like the following:

#!/usr/bin/env node
const tiny = require('tiny-json-http')

console.log('praise cage')
getImage()

async function getImage() {
  const result = await tiny.get({ url: 'https://light-28e-staging.begin.app' })
  console.log(result.body.image)
}
Enter fullscreen mode Exit fullscreen mode

The URL that you need to fetch should match the one from your deployed Begin API.

Finally, you can publish your CLI package to npm with npm publish.

Now anyone can run the command npx praise-cage-cli and they will be greeted with an image of The One True Cage.

Top comments (0)