Skip to content

Instantly share code, notes, and snippets.

@tonyxu-io
Last active June 25, 2018 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyxu-io/5294a5da3c3861aa8b3e8d55a3446c6a to your computer and use it in GitHub Desktop.
Save tonyxu-io/5294a5da3c3861aa8b3e8d55a3446c6a to your computer and use it in GitHub Desktop.
REST API Call Sample Code #snippet
// Vanilla JS - GET
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://reqres.in/api/users', true);
xhr.onload = function () {
console.log(xhr.responseText)
};
xhr.send(null);
// Vanilla JS - POST
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://reqres.in/api/users', true);
xhr.onload = function () {
console.log(xhr.responseText)
};
xhr.send({"name": "tony", "job": "engineer"});
// JQuery Ajax - GET
$.ajax({
url: 'https://reqres.in/api/users',
type: 'get',
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
// JQuery Ajax - POST
$.ajax({
url: 'https://reqres.in/api/users',
type: 'post',
data: {
"name": "morpheus",
"job": "leader"
},
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
import requests
import json
import urllib
# GET Request
url = 'https://reqres.in/api/users'
getResponse = requests.get(url)
# Print Response Status Code and Body
print getResponse.status_code, getResponse.text
# Convert response to JSON
jsonGetResponse = json.loads(getResponse.text)['data']
for user in jsonGetResponse:
print user['first_name'], user['last_name']
#################################
# POST requests
url = 'https://reqres.in/api/users'
data = {"name": "John", "job": "Engineer"}
postResponse = requests.post(url, json=data)
# Print Response Status Code and Body
print postResponse.status_code, postResponse.text
# Convert response to JSON
jsonPostResponse = json.loads(postResponse.text)
print jsonPostResponse['createdAt']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment