why do we use "post" method instead of "get" method in Rest Api

Madhan007
Tera Contributor

Hi all,
We had an Integration Requirement where we pass the 'Name' parameter in the Rest Api message and get the respective 'ID' in return. But for this,  I dont Understand why POST method has been used instead of GET method. Please pour your insights into this.

Thank you!

1 ACCEPTED SOLUTION

Robbie
Kilo Patron
Kilo Patron

Hi @Madhan007,

 

Interesting question. Do you know if there were/are any security concerns with the ID or data being returned? The only justification I've seen previously for using a 'post' method rather than a 'get' method is because the data sent is part of the URL with a 'get'.

Additionally, a 'post' is not cached and parameters are not saved in the browser history.

 

I'd steer you the below for a quick overview of the differences and let you determine what's best, however, generally, your spidey senses are correct. This would normally be a 'get'

 

To help others (or for me to help you more directly), please mark this response correct by clicking on Accept as Solution and/or Helpful.

 

Thanks, Robbie

 

The following table compares the two HTTP methods: GET and POST. (Source: W3C)

  GET POST
BACK button/ReloadHarmlessData will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
BookmarkedCan be bookmarkedCannot be bookmarked
CachedCan be cachedNot cached
Encoding typeapplication/x-www-form-urlencodedapplication/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
HistoryParameters remain in browser historyParameters are not saved in browser history
Restrictions on data lengthYes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)No restrictions
Restrictions on data typeOnly ASCII characters allowedNo restrictions. Binary data is also allowed
SecurityGET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
VisibilityData is visible to everyone in the URLData is not displayed in the URL

View solution in original post

8 REPLIES 8

Danish Bhairag2
Tera Sage
Tera Sage

Hi @Madhan007 ,

 

POST Method is used whenever we want to create a record in the target system. So for eg if u want to create a incident in some tool/instance u will pass certain parameters such as Short description description etc & in return u will receive the number which is created on the target tool or instance.

 

So to create a record via API's POST method is used.

 

Thanks,

Danish

This is interesting @DanishBhairag2 . I am having an issue at the moment where I do a GET via a script in a Scheduled Job to an external dbase, and I am only receiving back Updates in the import set and not Inserts.

Can you verify if this is my issue with the below script, and if I should be using POST instead and how in the script?

This is my Scheduled Job Script:

try {
    var r = new sn_ws.RESTMessageV2('ConnectWise', 'Default GET');
    r.setStringParameterNoEscape('yesterdayFormatted', gs.getProperty('connectwise.currentDateTime'));
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    var parsed = JSON.parse(responseBody);

    var statusCodesProperty = gs.getProperty('http.response.status.codes');
    var httpStatusCodeArray = statusCodesProperty.split(', ');

    //Check if httpStatus exists in the array
    if (httpStatusCodeArray.indexOf(httpStatus.toString()) !== -1) {
        var crImpSet = new GlideRecord('sys_import_set');
        crImpSet.initialize();
        crImpSet.mode = 'asynchronous';
        crImpSet.table_name = 'u_connectwise_asset_data';
        crImpSet.state = 'loading';
        crImpSet.insert();

        var restGR = new GlideRecord('u_connectwise_asset_data');
        for (var i = 0; i < parsed.length; i++) {
            restGR.initialize();
            restGR.u_config_recid = parsed[i].id;
            restGR.u_configuration_type = parsed[i].type.name;
            restGR.u_status = parsed[i].status.name;
            restGR.u_company = parsed[i].company.name;
            restGR.u_expires = parsed[i].warrantyExpirationDate;
            restGR.u_serial_number = parsed[i].serialNumber;
            restGR.u_model_number = parsed[i].modelNumber;
            restGR.u_vendor = parsed[i].vendor.name;
            restGR.u_tag_number = parsed[i].tagNumber;
            restGR.u_contact = parsed[i].contact.name;
            restGR.u_installed = parsed[i].installationDate;
            restGR.u_locations = parsed[i].location.name;
            restGR.u_site_name = parsed[i].site.name;
            restGR.u_purchased = parsed[i].purchaseDate;
            restGR.u_manufacturer = parsed[i].manufacturer.name;

            restGR.sys_import_set = crImpSet.sys_id;
            restGR.insert();
        }
    }
    crImpSet.state = "loaded";
    crImpSet.load_completed = gs.nowDateTime();
    gs.setProperty('connectwise.currentDateTime', crImpSet.load_completed.getDisplayValue());
    crImpSet.update();

    var transformer = new GlideImportSetTransformer();
    transformer.transformAllMaps(crImpSet); //Transform the import set rows
    if (transformer.isError()) {
        gs.error('Error executing the transform');
    }
} catch (ex) {
    var message = ex.message;
}

This is my ResponseBody

{
        "id": 19192,
        "name": "CWRR213",
        "type": {
            "id": 25,
            "name": "PC/Notebook",
            "_info": {
                "type_href": ""
            }
        },
        "status": {
            "id": 1,
            "name": "Active",
            "_info": {
                "status_href": ""            }
        },
        "company": {
            "id": 2791,
            "identifier": "RANDOM",
            "name": "Random Ltd",
            "_info": {
                "company_href": ""
            }
        },
        "contact": {
            "id": 12225,
            "name": "Random",
            "_info": {
                "contact_href": ""
            }
         },
        "deviceIdentifier": "",
        "serialNumber": "1234567",
        "modelNumber": "ThinkPad L480",
        "tagNumber": "A0012345",
        "installationDate": "2019-06-04T10:51:33Z",
        "warrantyExpirationDate": "2022-07-08T00:00:00Z",
        "vendorNotes": "",
        "notes": "Location Jan 2023 Sesame St Site Audit: Admin Office     \nHad a Sticker that has since worn off (old Asset Tag: A004321)\n\n123456 - User Exit: Joe Bloggs - appears to be a shared machine ",
        "macAddress": "",
        "lastLoginName": "",
        "billFlag": false,
        "backupSuccesses": 0,
        "backupIncomplete": 0,
        "backupFailed": 0,
        "backupRestores": 0,
        "backupServerName": "",
        "backupBillableSpaceGb": 0.00,
        "backupProtectedDeviceList": "",
        "backupYear": 0,
        "backupMonth": 0,
        "ipAddress": "",
        "defaultGateway": "",
        "osType": "",
        "osInfo": "",
        "cpuSpeed": "",
        "ram": "",
        "localHardDrives": "",
        "manufacturer": {
            "id": 12,
            "name": "Lenovo",
            "_info": {
                "manufacturer_href": ""
            }
        },
        "questions": [
             
            {
                "answerId": 60742,
                "questionId": 289,
                "question": "IMEI",
                "sequenceNumber": 3.00,
                "numberOfDecimals": 0,
                "fieldType": "Text",
                "requiredFlag": false
            }
        ],
        "activeFlag": true,
        "managementLink": "",
        "remoteLink": "",
        "mobileGuid": "",
        "companyLocationId": 72,
        "showRemoteFlag": false,
        "showAutomateFlag": false,
        "needsRenewalFlag": false,
        "manufacturerPartNumber": "",
        "_info": {
            "lastUpdated": "2024-05-29T01:15:00Z",
            "updatedBy": "",
            "dateEntered": "2019-06-27T06:31:55Z",
            "enteredBy": ""
        },
 "customFields": [
 {
                "id": 55,
                "caption": "Disposal Date",
                "type": "Date",
                "entryMethod": "EntryField",
                "numberOfDecimals": 0
            },
            {
                "id": 80,
                "caption": "Date Last Sighted",
                "type": "Date",
                "entryMethod": "EntryField",
                "numberOfDecimals": 0,
                "value": "2024-05-29T00:00:00Z"
            }
			
			     ]
    },

Robbie
Kilo Patron
Kilo Patron

Hi @Madhan007,

 

Interesting question. Do you know if there were/are any security concerns with the ID or data being returned? The only justification I've seen previously for using a 'post' method rather than a 'get' method is because the data sent is part of the URL with a 'get'.

Additionally, a 'post' is not cached and parameters are not saved in the browser history.

 

I'd steer you the below for a quick overview of the differences and let you determine what's best, however, generally, your spidey senses are correct. This would normally be a 'get'

 

To help others (or for me to help you more directly), please mark this response correct by clicking on Accept as Solution and/or Helpful.

 

Thanks, Robbie

 

The following table compares the two HTTP methods: GET and POST. (Source: W3C)

  GET POST
BACK button/ReloadHarmlessData will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
BookmarkedCan be bookmarkedCannot be bookmarked
CachedCan be cachedNot cached
Encoding typeapplication/x-www-form-urlencodedapplication/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
HistoryParameters remain in browser historyParameters are not saved in browser history
Restrictions on data lengthYes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)No restrictions
Restrictions on data typeOnly ASCII characters allowedNo restrictions. Binary data is also allowed
SecurityGET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
VisibilityData is visible to everyone in the URLData is not displayed in the URL

saurabh_dubey
Kilo Sage

Is it done through the scripted rest api,

 

Then there might be the condition if "Name" parameter exists the return the respective ID, else do the POST request update/insert. 

Generally the coder might be lazy and wanted to fit every thing in one and let the code to handle every thing.

 

If you found my answer correct do mark it helpful.

 

Thanks

Saurabh.