Create a API with google sheets

Create a API with google sheets

APIs can be very useful for different situations but they can also be difficult to program, so in today’s article I am going to show you how to create a simple API with the help of google spreadsheets.

In this tutorial we are going to use our api to create a web application

Prerequisites

  • A Google account

Setting up the spreadsheet

The first thing we need to do is create a spreadsheet in sheets.new .Next click on the tools menu and then click on the script editor button as shown in the picture.

content_1609340197325-2.png

Creating the web application server

To collect data, we need to be able to capture the GET or POST request sent by the data source.You can use the code I show below to start using the api.

function doGet(e) {

    return ContentService.createTextOutput("This is an example GET post!");
}
function doPost(e) {
    var sheet = SpreadsheetApp.getActiveSheet();


    var body = JSON.parse(e.postData.contents)
    sheet.appendRow(\[body.id,
    body.date_created,
    body.first_name,
    body.email,
    \])
}

Publishing the web application

For our web app to be visible we must publish it, to publish it we must go to the publish menu and then click on the button deploy as web app.Then in the menu click on make the web visible to everyone, even anonymous.

content_1609340554840.png

Now you can visit the url that resulted and you will see the following message means that all is working: This is an example GET post!

Testing the functions

To test if our system works you can go to this page reqbin.com to send a post request.You can use the following json code to make the post request:

{
    "id": 1,
    "date_created": "24-11-2020 10:10 PM",
    "name": "Example",
    "email": "test@example.com"
}

Once the post request is sent, you can see that the data has been sent to the spreadsheet.

Did you find this article valuable?

Support blog • dglobal by becoming a sponsor. Any amount is appreciated!