We help IT Professionals succeed at work.

POSTING JSON TO API

FSAAdmin
FSAAdmin asked
on
Looking for an example of passing JSON to a server API.  I've had help getting the JSON created from HTML Form Elements, now I need to pass this on to the API.
Comment
Watch Question

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
https://api.jquery.com/jquery.post/

var yourjson = {
    n: 1,
    b: true,
    s: "hello" 
};
$.post( "/path/to/api", yourjson, function( data ) {
}, "json);

Open in new window

ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:

Here an example without jQuery:

<html> 
<head> 
<title>JSON API</title> 
<style> 
input, select { 
	width: 300px; 
} 
</style> 
<script> 
var req = { 
	"request": { 
        "subject": "Unable to fetch mails", 
        "description": "I am unable to fetch mails from the mail server", 
        "requester": { 
            "id": "4", 
            "name": "administrator" 
        }, 
        "impact_details": "Routine tasks are pending due to mail server problem", 
        "resolution": { 
            "content": "Mail Fetching Server problem has been fixed" 
        }, 
        "status": { 
            "name": "Open" 
        } 
    } 
} 
var fldMap = { 
	"request.subject":"subject", 
	"request.description":"description", 
	"request.requester.id":"requester_id", 
	"request.requester.name":"requester_name", 
	"request.resolution.content":"resolution", 
	"request.status.name":"status" 
} 
 
window.onload = function(){ 
	var elements = document.forms[0].elements; 
	for(var item in fldMap){ 
		elements[fldMap[item]].value = getObjVal(req, item);	 
	} 
} 
 
function getObjVal(oBase, oPath){ 
	var oElem = oPath.split('.'); 
	if(oElem.length == 1){ 
		return oBase[oElem[0]]; 
	} 
	oBase = oBase[oElem[0]]; 
	oElem.shift();  
	return getObjVal(oBase, oElem.join('.')); 
} 
 
 
function setObjVal(oBase, oPath, oValue){	 
	var oElem = oPath.split('.'); 
	if(oElem.length == 1){ 
		oBase[oElem[0]] = oValue; 
	} else { 
		oBase = oBase[oElem[0]]; 
		oElem.shift();  
		setObjVal(oBase, oElem.join('.'), oValue); 
	} 
} 
 
function callJsonAPI(theForm){ 
	var elements = theForm.elements; 
	for(var item in fldMap){ 
		setObjVal(req, item, elements[fldMap[item]].value);	 
	} 
	fetch('https://jsonplaceholder.typicode.com/posts', { 
		method: 'POST', 
		body: JSON.stringify(req), 
		headers: { 
			"Content-type": "application/json; charset=UTF-8" 
		} 
	}) 
	.then(response => response.json()) 
	.then(json => theForm.result.value="Response from typicode.com:\n"+JSON.stringify(json).replace(/\,/g,',\n')) 
} 
</script> 
</head> 
<body> 
<form> 
<h1>JSON form</h1> 
<table> 
<tr><th>Subject:</th><td><input type="text" name="subject" ></td></tr> 
<tr><th>Description:</th><td><input type="text" name="description" ></td></tr> 
<tr><th>Requester ID:</th><td><input type="text" name="requester_id" ></td></tr> 
<tr><th>Requester Name:</th><td><input type="text" name="requester_name" ></td></tr> 
<tr><th>Resolution:</th><td><input type="text" name="resolution" ></td></tr> 
<tr><th>Status:</th><td><input type="text" name="status" ></td></tr> 
<tr><td></td><td><input type="button" value="Submit" onClick="callJsonAPI(this.form)" ></td></tr> 
</table> 
<textarea name="result" cols="80" rows="12" > 
</textarea> 
</form> 
<body> 
</html>
ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:

Author

Commented:
I'm having to build for two different versions of the API as we have two different instances.  

They both require paramaters to be inserted into the URL and an additional header for authtoken

version 1: authtoken, scope, OPERATION_NAME (value is ADD_REQUEST) and INPUT_DATA (value is JSON)
Expected: http://someserver/sdpapi/request?OPERATION_NAME=ADD&TECHNICIAN_KEY=11111&INPUT_DATA=(json)

version 2: authtoken, and input_data
Expected: http://someserver/api/v3/requests?input_data=(json) 

So it seems like the body of the json can be empty and everything is embedded in the URL.
Systems architect
CERTIFIED EXPERT
Top Expert 2006
Commented:

Here again the version with the two variants that you asked for.

But keep in mind that you ONLY learn when you make own mistakes. So do it! And come back when something blocks you for long time  :  )


<html> 
<head> 
<title>JSON 2 APIs</title> 
<style> 
input, select { 
	width: 300px; 
} 
</style> 
<script> 
var req = { 
	"request": { 
        "subject": "Unable to fetch mails", 
        "description": "I am unable to fetch mails from the mail server", 
        "requester": { 
            "id": "4", 
            "name": "administrator" 
        }, 
        "impact_details": "Routine tasks are pending due to mail server problem", 
        "resolution": { 
            "content": "Mail Fetching Server problem has been fixed" 
        }, 
        "status": { 
            "name": "Open" 
        } 
    } 
} 
var fldMap = { 
	"request.subject":"subject", 
	"request.description":"description", 
	"request.requester.id":"requester_id", 
	"request.requester.name":"requester_name", 
	"request.resolution.content":"resolution", 
	"request.status.name":"status" 
} 
 
window.onload = function(){ 
	var elements = document.forms[0].elements; 
	for(var item in fldMap){ 
		elements[fldMap[item]].value = getObjVal(req, item);	 
	} 
} 
 
function getObjVal(oBase, oPath){ 
	var oElem = oPath.split('.'); 
	if(oElem.length == 1){ 
		return oBase[oElem[0]]; 
	} 
	oBase = oBase[oElem[0]]; 
	oElem.shift();  
	return getObjVal(oBase, oElem.join('.')); 
} 
 
 
function setObjVal(oBase, oPath, oValue){	 
	var oElem = oPath.split('.'); 
	if(oElem.length == 1){ 
		oBase[oElem[0]] = oValue; 
	} else { 
		oBase = oBase[oElem[0]]; 
		oElem.shift();  
		setObjVal(oBase, oElem.join('.'), oValue); 
	} 
} 
 
function callJsonAPI_1(theForm){ 
	var elements = theForm.elements; 
	for(var item in fldMap){ 
		setObjVal(req, item, elements[fldMap[item]].value);	 
	} 
	fetch('https://jsonplaceholder.typicode.com/posts?OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=11111&INPUT_DATA=('+JSON.stringify(req)+')', { 
		method: 'GET', 
		headers: { 
			"Content-type": "application/json; charset=UTF-8" 
		} 
	}) 
	.then(response => response.json()) 
	.then(json => theForm.result.value="Response from typicode.com:\n"+JSON.stringify(json).replace(/\,/g,',\n')) 
} 
 
function callJsonAPI_2(theForm){ 
	var elements = theForm.elements; 
	for(var item in fldMap){ 
		setObjVal(req, item, elements[fldMap[item]].value);	 
	} 
	fetch('https://jsonplaceholder.typicode.com/posts?INPUT_DATA=('+JSON.stringify(req)+')', { 
		method: 'GET', 
		headers: { 
			"Content-type": "application/json; charset=UTF-8", 
			"authtoken": "abcdef123456789", 
			 
		} 
	}) 
	.then(response => response.json()) 
	.then(json => theForm.result.value="Response from typicode.com:\n"+JSON.stringify(json).replace(/\,/g,',\n')) 
} 
</script> 
</head> 
<body> 
<form> 
<h1>JSON form</h1> 
<table> 
<tr><th>Subject:</th><td><input type="text" name="subject" ></td></tr> 
<tr><th>Description:</th><td><input type="text" name="description" ></td></tr> 
<tr><th>Requester ID:</th><td><input type="text" name="requester_id" ></td></tr> 
<tr><th>Requester Name:</th><td><input type="text" name="requester_name" ></td></tr> 
<tr><th>Resolution:</th><td><input type="text" name="resolution" ></td></tr> 
<tr><th>Status:</th><td><input type="text" name="status" ></td></tr> 
<tr><td></td><td><input type="button" value="Submit API 1" onClick="callJsonAPI_1(this.form)" ></td></tr> 
<tr><td></td><td><input type="button" value="Submit API 2" onClick="callJsonAPI_2(this.form)" ></td></tr> 
</table> 
<textarea name="result" cols="80" rows="12" > 
</textarea> 
</form> 
<body> 
</html>
Chinmay PatelChief Technology Ninja
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:

I would strongly recommend going with Fetch. It can get tricky but it is one of the best thing that I have come across.

ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:

...and if you get old IE9 users tell them there is Edge Chromium out  :  )

Chinmay PatelChief Technology Ninja
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:

Zvonko :P If you have IE9 users... well.. time to quit :D and find other job / client :P

ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:

I am retiered  <|:-)

Chinmay PatelChief Technology Ninja
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:

Aahhh.. the sweet joy... but do we really ... truly retire... ever? :)

ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:

That was what my colleagues told me: you will see, only the management changes  :  )

Author

Commented:
Thank you Zvonko.  I'm working through some issues on the server side and believe you have helped me out

Author

Commented:
Thank you Zvonko.  I'm working through some issues on the server side and believe you have helped me out