Hello, Guys welcome back to Learn How to Handle GET and POST HTTP Requests in Google Apps Script easily.
Using the HTML service, you may simply develop a Web App that offers HTML, JSON, XML, or plain text output with Google Apps Script. When you publish a Google Script project as a web app, it receives a public URL (think API) that can be invoked from external applications using HTTP GET or POST requests with query parameters and request body.
When releasing the script as a web app, select “Allow anonymous access” and run the script as yourself. If you make changes to the script, make a new version in the script editor and deploy the most recent version. Also Learn How to Factory Reset your Gmail Account in easy steps and Learn How to Use Images in Gatsby easily
Here are some examples of how to convert your Google Script into a web API by including the doGet and doPost methods to your project.
Handling GET Requests
At the point when a content is distributed as a web application, the doGet callback work handles generally GET demands made to the content’s public URL. The Google Script can return plain text content, HTML or JSON information as displayed in the models underneath:
Return Text Content
const doGet = (event = {}) => {
const { parameter } = event;
const { name = 'Anonymous', country = 'Unknown' } = parameter;
const output = `Hello ${name} from ${country}`;
return ContentService.createTextOutput(output);
};
Any question boundaries added to the Google Script URL, similar to name and country in our model, become accessible in the parameter property of the event object of the doGet and doPost techniques in Apps Script.
https://script.google.com/macros/s/12345/exec?name=Amit&country=India
If something is not working, you can always log the request object to the StackDrive console logs and easily debug the full request.
console.log(`doGet`, JSON.stringify(event));
Serve JSON Output
A similar ContentService can be utilized to return JSON yield by utilizing the setMimeType method with the emulate set as ContentService.MimeType.JSON.
const doGet = (event = {}) => {
const { parameter } = event;
const { name = 'Anonymous', country = 'Unknown' } = parameter;
const message = `Hello ${name} from ${country}`;
const json = { name, country, message };
return ContentService.createTextOutput(JSON.stringify(json)).setMimeType(ContentService.MimeType.JSON);
};
When testing HTTP demands in Google Script with utilities like CURL or Postman, guarantee that that “Naturally follow diverts Follow HTTP 3xx reactions as sidetracks” setting is turned on since the ContentService serves a 301 divert from the script.googleusercontent.com domain.
Serving HTML Content
Your Google Apps script undertaking can serve HTML website pages with the HtmlService service. The site pages presented with App Script included Google cautioning header at the top however it very well may be taken out on the off chance that you install the Google Script in another page (like Google Sites) with the IFRAME tag.
const doGet = (event = {}) => {
const { parameter } = event;
const { name = 'Anonymous', color = 'Black' } = parameter;
const html = `<p><b>${name}'s</b> favorite color is <font color="${color}">${color}</font></p>`;
return HtmlService.createHtmlOutput(html)
.setTitle('Apps Script Webpage')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
};
You should set the X-Frame-Options header of the site page to XFrameOptionsMode.ALLOWALL to permit different pages to insert your Google Script HTML page.
Handle POST Requests with Google Scripts
The callback function doPost is summoned when a HTTP POST solicitation is make to your Google Script URL that is distributed as a web application with unknown access.
const doPost = (request) => {
console.log(request);
return ContentService.crateTextOutput(JSON.stringify(request));
};
The request argument of the doPost method can include:
- queryString -The name-esteem sets sent in the URL of the solicitation (name=Mike&age=12)
- parameter -The question string name-esteem sets are additionally available inside the boundary object like GET demands (e.paremeter.name or e.parameter.age).
- postData -The substance property of the postData object incorporates the POST body and type property of postData indicates the MIME sort of the post body. It can have values like application/x-www-structure urlencoded (key-esteem sets isolated by the ‘and’ character and each key is isolated from its encoded esteem by ‘=’), application/json for JSON information or text/plain for text body.
For parallel information, like file transfers, the HTTP post solicitation is sent with the multipart/structure data mime type. For the situation of application/x-www-structure urlencoded, the queryString is set as a component of the POST solicitation body.
const doPost = (request = {}) => {
const { parameter, postData: { contents, type } = {} } = request;
const { source } = parameter;
if (type === 'application/json') {
const jsonData = JSON.parse(contents);
return ContentService.createTextOutput(JSON.stringify(jsonData));
}
if (type === 'application/x-www-form-urlencoded') {
const json = {};
contents
.split('&')
.map((input) => input.split('='))
.forEach(([key, value]) => {
json[decodeURIComponent(key)] = decodeURIComponent(value);
});
return ContentService.createTextOutput(JSON.stringify(json));
}
return ContentService.createTextOutput(contents);
};
Testing HTTP Requests with Google Scripts
You can utilize Postman, RequestBin, CURL or any of your favorite dev tool to send GET and POST solicitations to your Apps Script administration. We’ll utilize Apps Script itself with the implicit UrlFetchApp administration to test the solicitation and reaction.
Working with HTTP GET Requests
In this model, the GET API coverts the inquiry string to JSON. The test function makeHttpGetRequest compares the provided question string esteem with the brought object back.
const doGet = (event = {}) => {
const { parameter } = event;
const { name, country } = parameter;
return ContentService.createTextOutput(JSON.stringify({ name, country })).setMimeType(ContentService.MimeType.JSON);
};
const makeHttpGetRequest = () => {
const queryString = '?name=Amit+Agarwal&country=India';
const apiUrl = ScriptApp.getService().getUrl();
const url = apiUrl + queryString;
const options = {
method: 'GET',
followRedirects: true,
muteHttpExceptions: true,
contentType: 'application/json',
};
const response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() == 200) {
const { country } = JSON.parse(response);
Logger.log('Country', country);
}
};
Working with HTTP GET Requests
The doPost strategy returns either the nation or the name from the solicitation body contingent upon the activity boundary of the content URL.
const doPost = (request = {}) => {
const { parameter, postData: { contents, type } = {} } = request;
const { name, country } = JSON.parse(contents);
if (parameter.action === 'getCountry') {
return ContentService.createTextOutput(country);
} else {
return ContentService.createTextOutput(name);
}
};
const makeHttpPostRequest = () => {
const url = ScriptApp.getService().getUrl() + '?action=getCountrdy';
const payload = {
name: 'Amit Agarwal',
blog: 'www.labnol.org',
country: 'India',
};
const options = {
method: 'POST',
followRedirects: true,
muteHttpExceptions: true,
payload: JSON.stringify(payload),
};
const response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() == 200) {
Logger.log(response.getContentText());
}
};
POST Request with HTML Forms
The following model uses a basic HTML structure that sends a POST solicitation with application/x-www-structure urlencoded mime type.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<form action="https://script.google.com/macros/s/#####/exec" method="POST" target="_blank">
<input type="text" name="name" />
<input type="text" name="country" />
<button type="submit">Submit</button>
</form>
</body>
</html>
The POST method returns the POST body of the request.
const doPost = (request = {}) => {
const { postData: { contents, type } = {} } = request;
return ContentService.createTextOutput(contents);
};
Using CURL to make HTTP Requests
The POST API returns a boundary from the inquiry line of the URL and the name from the solicitation body.
const doPost = (request = {}) => {
const { parameter, postData: { contents, type } = {} } = request;
const data = JSON.parse(contents);
return ContentService.createTextOutput(parameter.secret + type + data.name);
};
CURL can be used to send a POST request to Google Script. Remember to use the -L parameter in order for curl to follow the redirect from script.google.com to googleusercontent.com.
curl -L \
-H 'Content-Type:application/json' \
-d '{"name": "Amit","country": "India"}' \
"https://script.google.com/macros/s/###/exec?secret=1234"
