How to use ChatGPT to make an instantly deployable Node.js REST API backend
Tags: webdev, chatgpt, serverless, node
Published: 2023-01-14 20:11:34

[ChatGPT](https://openai.com/blog/chatgpt/), a variant of the popular GPT-3 language model, is revolutionizing the way we produce text and programming code. 

In this blog post, we will demonstrate how ChatGPT can be used to produce high-quality, easy-to-understand, and instantly deployable Node.js backend code using examples from [codehooks.io](https://codehooks.io).

By the end of this post, you will have a powerful tool to quickly prototype and build various types of backends with minimal effort. Let's dive in and see how ChatGPT can enhance your development process!

A variant of this blogpost was originally published on the [codehooks.io blog](https://codehooks.io/blog)

## Making a database-powered CRUD REST API with ChatGPT

We thought that ChatGPT could be a good match for creating code for codehooks.io due to codehooks' serverless and "instant deploy without setup" capability along with its built-in database, jobs and worker queue features. 

One problem we figured out we might have was due to the fact that codehooks.io was released in late 2022 and ChatGPT has only been trained on data up to 2021. However, after experimenting a bit, we figured out a way to ask ChatGPT by providing an example instantly.

### How to ask ChatGPT for help with coding

If you haven't [signed up for ChatGPT](https://chat.openai.com/auth/login) yet, you must do so before you can talk to it. To create our question for creating a CRUD REST API for deployment with codehooks.io using the [codehooks-crudlify-yup](https://www.npmjs.com/package/codehooks-crudlify-yup) NPM package, we copied the following code from one of our [blog posts](https://codehooks.io/blog/how-to-quickly-create-a-crud-rest-api-backend-using-codehooks-io-with-code-example#a-minimal-crud-api-code-example):

```js
/*
* Minimal CRUD API code example using Yup schema
*/
import app from 'codehooks-js'
import crudlify from 'codehooks-crudlify-yup'
import * as yup from 'yup';

// "product" schema allowing any json object
const product = yup.object().shape({
    json: yup.mixed()
})

// Add CRUD routes with yup schema for two collections
crudlify(app, {product})

// bind to serverless runtime
export default app.init()
```

> 💡 _Create database-backed REST APIs fast with crudlify_ ⚡️
When you need a "standard" REST API with NoSQL database support, using the library 'codehooks-crudlify-yup' must be one of the simplest ways to do it with code. The library generates the common REST API routes: GET, POST, PUT, PATCH and DELETE and persists the data in the codehooks.io NoSQL database. You can also query the data quite easily.

Then we added the following text before this code: "This is an example of codehooks.io backend code:", and we added this after the code: " Can you create a codehooks.io backend like this with a more complete example for an online shop."

![The question we asked ChatGPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfjrewakzsb7vdif9wp1.png)

And voilá! This is the code we got back from ChatGPT:

```js
import app from 'codehooks-js'
import crudlify from 'codehooks-crudlify-yup'
import * as yup from 'yup';

// Define the schema for the "Product" collection
const productSchema = yup.object().shape({
    name: yup.string().required(),
    description: yup.string(),
    price: yup.number().required(),
    image: yup.string().url(),
    category: yup.string().required(),
    ratings: yup.array().of(yup.number())
});

// Define the schema for the "Order" collection
const orderSchema = yup.object().shape({
    customerName: yup.string().required(),
    customerEmail: yup.string().email().required(),
    products: yup.array().of(yup.object().shape({
        productId: yup.string().required(),
        quantity: yup.number().required()
    })),
    total: yup.number().required(),
    status: yup.string().oneOf(['pending', 'shipped', 'delivered'])
});

// Add CRUD routes for the "Product" and "Order" collections with the corresponding schemas
crudlify(app, { products: productSchema, orders: orderSchema });

// Bind the app to the serverless runtime
export default app.init();
```

This was the explanation ChatGPT helpfully provided:

> This code creates two collections for Product and Order, defined by the productSchema and orderSchema respectively. The schema of product includes name, description, price, image, category and ratings. The schema of order includes customerName, customerEmail, products, total, status.It also demonstrates the use of different validation techniques like required, email, url and oneOf() for various fields in the collection.
It can be more fine-tuned based on the specific needs of the backend.
Please note that this is just an example to give you an idea of how you can define your collections and schemas, and you may need to adjust it to fit the specific requirements of your application.

### Deploying the AI-generated Node.js JavaScript code directly without touching it 💥🤖

This code certainly looks correct at first glance. I have, however, several times caught ChatGPT "inventing" totally new libraries and methods and got an excuse afterwards when I pinpointed it 😂

Let's deploy the code! If you want to do this yourself, follow the instructions in our [Quick Start](https://codehooks.io/docs) to get ready. It only takes a few seconds.

First, create a new project:

```bash
codehooks create shopbackend
```

This [CLI command](https://codehooks.io/docs/cli) creates a codehooks project, adds a folder named "shopbackend" and initializes a "hello world" index.js JavaScript file.

Replace the contents of the "index.js" file with ChatGPTs generated code above and save it.

You also need to install the necessary npm packages:

```bash
npm i codehooks-js codehooks-crudlify-yup yup
```

In the same folder as index.js, run the deploy command:

```bash
codehooks deploy
```
Result:
```bash
Project: shopbackend-h3r5  Space: dev
Deployed Codehook successfully! 🙌 
```
Yes! 🙌 

It worked...or rather it compiled and was deployed correctly by codehooks.io.

Let's test the backend by adding some products using cURL (we also recommend [Postman](https://postman.com)).

> **Postman Import button**
Using the "Import" button in Postman, you can directly import cURL commands and then use it to test your API endpoints.

This 'info' command is very useful when we need more information about our space AND need some cURL examples:

```bash
codehooks info --examples
```

This is what we get: 

```bash
Project name: shopbackend-h3r5
Team: Martin Tornes (personal account)

API endpoint:  https://shopbackend-h3r5.api.codehooks.io/dev

Examples in cURL:

curl https://shopbackend-h3r5.api.codehooks.io/dev/myroute -H 'x-apikey: 27b3822e-ecf3-4263-bcee-24acd6aed2d0' -H 'Content-Type: application/json'

curl --request POST https://shopbackend-h3r5.api.codehooks.io/dev/myroute -H 'x-apikey: 27b3822e-ecf3-4263-bcee-24acd6aed2d0' -H 'Content-Type: application/json' --data-raw '{"name": "Mr. Code Hooks", "active": true }'

Spaces:
┌──────────────┬────────────────────────────────────────────┬───────────────┬──────┬──────┐
│ Name         │  Tokens                                    │ Allowed Hosts │ Jwks │  Env │
├──────────────┼────────────────────────────────────────────┼───────────────┼──────┼──────┤
│ dev (active) │ 27b3822e-ecf3-4263-bcee-24acd6aed2d0 (RW)  │               │      │      │
└──────────────┴────────────────────────────────────────────┴───────────────┴──────┴──────┘

Project members:
┌────────────────────┬──────────────────────────────────┬───────┐
│ name               │ email                            │ role  │
├────────────────────┼──────────────────────────────────┼───────┤
│ Martin Tornes      │ martintornesdev@gmail.com        │ ADMIN │
└────────────────────┴──────────────────────────────────┴───────┘
```

Let's modify the POST cUrl to add some product data. We'll add a JSON structure with at least the fields ChatGPT marked as required:

```bash
curl --request POST https://shopbackend-h3r5.api.codehooks.io/dev/products \
-H 'x-apikey: 27b3822e-ecf3-4263-bcee-24acd6aed2d0' \
-H 'Content-Type: application/json' \
--data-raw '{"name": "Codehook", "price": 0, "category": "TOOLS" }'
```

Result: 
```bash
{"name":"Codehook","price":0,"category":"TOOLS","_id":"185a3157a34-u96ow26u9zcxd0"}
```
It worked! You can now use your preferred programming language and library to interact with this REST API and database. 

## Conclusion

codehooks.io is a good fit for getting a lot of help from ChatGPT, you just need to show it an example before you ask a question. The way we demonstrated it here works fine, but there are probably multiple ways to get the most out of it. 

We also asked it to create a scheduled "CRON" job using codehooks.io job "hooks", which should Tweet each afternoon at 5pm. It produced working code using Twitter's library and the correct codehooks.io JavaScript code. Ready to deploy!

We could have asked it to do more to elaborate on the code it created. This type of dialog is in fact the recommended way to work with it to produce the best results. We'll leave that to a later blogpost or a whole dedicated section where we add ChatGPT examples.

ChatGPT is a glimpse into an exciting future of AI-assisted programming. It's not exactly NoCode, but it surely is automated and saves a ton of time. 

Disclaimer... Some parts of this blog post was written with help from ChatGPT 😉