Last active
June 25, 2018 03:19
-
-
Save tonyxu-io/5294a5da3c3861aa8b3e8d55a3446c6a to your computer and use it in GitHub Desktop.
REST API Call Sample Code #snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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