Robert Granlund
asked on
JSON POST EXAMPLE
JSON POST. Can anyone show me a simple example of a JSON POST?
https://www.meetup.com/mee tup_api/ provides a good example of a family of API calls.
There are 1000s of other API services online you can use as examples also.
Maybe best to expand your question to state...
1) If you're building an API, purpose of API.
2) If you're having problems calling an API, provide your POST call along with the error you received.
There are 1000s of other API services online you can use as examples also.
Maybe best to expand your question to state...
1) If you're building an API, purpose of API.
2) If you're having problems calling an API, provide your POST call along with the error you received.
ASKER
On a website there is a form that you fill in your name and email. The info is posted to the MarketCircle API, where the "Opportunity" info is stored. I want to use javascript to connect to the API and send the information but I'm not 100% certain on where to start. POSTing to an API is new to me. (among other aspects of working with an API)
Here is the do: https://developer.marketcircle.com/v1/reference#opportunity-create
Here is the do: https://developer.marketcircle.com/v1/reference#opportunity-create
The URL above has all you require to access the data.
One example...
Where $redacted looks to be a token provided in your Market Circle dashboard.
You must login to access your token.
That's all you require.
One example...
curl -v -H "Authorization: Bearer $redacted" https://api.marketcircle.net/v1/opportunities/types
Where $redacted looks to be a token provided in your Market Circle dashboard.
You must login to access your token.
That's all you require.
Here is a jQuery example
var obj = {
name: 'Clark Kent',
alterego: 'Superman'
};
$.ajax({
url: 'registerhero.php',
type: 'post',
data: JSON.stringify(obj), // YOU MUST CONVERT DATA TO JSON BEFORE SENDING
dataType: 'JSON', // NOTE THIS HAS ONLY TO DO WITH THE DATA RECEIVED
// IT IS NOT A REQUIREMENT FOR SENDING DATA
contentType: "application/json", // REQUIRED TO SEND JSON
}).then(function(resp) {
// THIS IS WHERE THE dataType: 'JSON' IS USED - TELLS jQuery
// THE RETURN DATA IS JSON - jQuery WELL NOW AUTOMATICALLY PARSE THE JSON
// AND RETURN THE RESULTING OBJECT
// ONLY USE IF API IS RETURNING JSON
})
Having said that in most cases API's do not allow direct access from webpages (for security reasons). Most (as in this case) require some sort of authentication and use a token to be able to use the API - if this was done in the browser the credentials would be out in the open.
If you attempt to make an AJAX call from your web page using the method above you are more than likely going to get a CORS error.
The solution is to do this in two stages
Stage 1 your form posts the data to a script you control (using the method described in my previous answer)
Stage 2 your server script then makes a server to server call with the correct API authentication and token exchange to retrieve the relevant data
Stage 3 your server script returns the data to your calling script.
How you do this is dependent on your server side environment. If you are using PHP you can use the cUrl library to make the call.
However there are a number of steps that are required here. The service you are using uses OAuth2 - you should familiarise yourself with that specification. OAuth requires you send Authorization information (credentials and tokens) as a header - you need to be familiar with how headers work.
What is your server environment?
If you attempt to make an AJAX call from your web page using the method above you are more than likely going to get a CORS error.
The solution is to do this in two stages
Stage 1 your form posts the data to a script you control (using the method described in my previous answer)
Stage 2 your server script then makes a server to server call with the correct API authentication and token exchange to retrieve the relevant data
Stage 3 your server script returns the data to your calling script.
How you do this is dependent on your server side environment. If you are using PHP you can use the cUrl library to make the call.
However there are a number of steps that are required here. The service you are using uses OAuth2 - you should familiarise yourself with that specification. OAuth requires you send Authorization information (credentials and tokens) as a header - you need to be familiar with how headers work.
What is your server environment?
ASKER
@david
So I use Curl to open the connection but how do I pass along name, address, email etc? I'm confused as to how I format the rest of the page.
So I use Curl to open the connection but how do I pass along name, address, email etc? I'm confused as to how I format the rest of the page.
ASKER
For example, here: https://developer.marketcircle.com/reference#company-create
And then click on Javascript
Is it saying that All I need to do is this? -
And then click on Javascript
Is it saying that All I need to do is this? -
<script>
var data = JSON.stringify({
"name": "Test Name",
"type": "Test Company",
"region": "MS",
"emails": [
{
"address": "info@MYSITE.com",
"label": "Email Address",
"note": "Company Email Address"
}
]
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.marketcircle.net/v1/companies");
xhr.send(data);
</script>
You are welcome to try that - not sure why they have put that example there but it won't work from a Web browser.
Try this
1. Open your console (F12) [Assume firefox
2. Open the scratchpad (above console on the right there are some icons - second from left should be scratchpad)
3. Paste your code in the scratchpad and run
Note the output in the console window
This is what I was referring to in my earlier post. Your code above is just a JavaScript version of the jQuery I posted. It is unlikely to work in practice for security reasons - their API would be wide open to abuse.
You are most likely going to need to relay this through your server script (PHP, ASP etc) - in which case we would need to know what you intend using before suggesting a solution.
Try this
1. Open your console (F12) [Assume firefox
2. Open the scratchpad (above console on the right there are some icons - second from left should be scratchpad)
3. Paste your code in the scratchpad and run
Note the output in the console window
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.marketcircle.net/v1/companies. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More]
This is what I was referring to in my earlier post. Your code above is just a JavaScript version of the jQuery I posted. It is unlikely to work in practice for security reasons - their API would be wide open to abuse.
You are most likely going to need to relay this through your server script (PHP, ASP etc) - in which case we would need to know what you intend using before suggesting a solution.
ASKER
If I use the cURL suggestion it has a token. But I'm not sure how to get the info into cURL. The example shows it like this here: https://developer.marketcircle.com/reference#company-create
Can I do:
curl --request POST \
--url https://api.marketcircle.net/v1/companies \
--data '{"name":"John Doe","category":"Test"}'
Can I do:
if(isset($_POST['name'])) {
$name = $_POST['name'];
$category = $_POST['category'];
--url https://api.marketcircle.net/v1/companies \
--data '{"name":$name,"category":$category}'
}
Ok so you are using PHP. In that case use the cUrl PHP library
https://www.php.net/manual/en/book.curl.php
The token is passed in the header so you would need to add a header to the cUrl request.
The samples on that site don't seem to be complete - at the top of the page they specifically mention you need to authorize. If you try and run those Curl samples directly you will get a 404.
The samples are misleading - I think best not to focus on them right now.
First you have to setup your code to make an Auth request to the service to get a token using your App key (Have you set that up already?)
https://www.php.net/manual/en/book.curl.php
The token is passed in the header so you would need to add a header to the cUrl request.
The samples on that site don't seem to be complete - at the top of the page they specifically mention you need to authorize. If you try and run those Curl samples directly you will get a 404.
The samples are misleading - I think best not to focus on them right now.
First you have to setup your code to make an Auth request to the service to get a token using your App key (Have you set that up already?)
ASKER
Do you mean like this:
I have a temp personal token from the developer account.
Also, are you saying that cURL needs to be setup on the server? The server where the form resides ?
curl -v -H "Authorization: Bearer $PERSONAL_TOKEN_HERE" https://api.marketcircle.net/v1
if(isset($_POST['name'])) {
$name = $_POST['name'];
$category = $_POST['category'];
--url https://api.marketcircle.net/v1/companies \
--data '{"name":$name,"category":$category}'
}
I have a temp personal token from the developer account.
Also, are you saying that cURL needs to be setup on the server? The server where the form resides ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I really appreciate this starting point.
ENDPOINTURL
$resp = $httpClient->post(ENDPOINT URL, json_encode($data));
As I read through it, it is starting to make sense. This last part though.
ENDPOINTURL
$resp = $httpClient->post(ENDPOINT
As I read through it, it is starting to make sense. This last part though.
Not sure if the last post contained an unfinished question?
ASKER
What does ENDPOINT URL mean?
That is the URL that you are connecting to - the API URL.
https://github.com/ethanre