Difference between revisions of "Python:REST"
Jump to navigation
Jump to search
m |
|||
Line 3: | Line 3: | ||
* Transports JSON-formatted data over HTTP | * Transports JSON-formatted data over HTTP | ||
* Stateless as the server does not hold client context (history). Pre: simple, Con: sometimes more requests needed. | * Stateless as the server does not hold client context (history). Pre: simple, Con: sometimes more requests needed. | ||
+ | |||
+ | Example code, fetching a file: | ||
+ | |||
+ | <syntaxhighlight lang=python> | ||
+ | #!/usr/bin/env python | ||
+ | |||
+ | import requests | ||
+ | import json | ||
+ | import sys | ||
+ | import urllib3 | ||
+ | |||
+ | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) | ||
+ | |||
+ | rest_host = "<servername>" | ||
+ | rest_url = "https://"+rest_host | ||
+ | command_url = "<filepath" | ||
+ | |||
+ | post_headers = '{"Content-Type":"application/json"}' | ||
+ | |||
+ | def main(): | ||
+ | rest_session = requests.Session() | ||
+ | response = rest_session.post(rest_url+"/login", | ||
+ | data={"USERNAME":<user>,"PASSWORD":<password>"}, | ||
+ | verify=False) | ||
+ | print "login status: "+str(response.status_code) | ||
+ | |||
+ | response = rest_session.get(rest_url+command_url,verify=False,stream=True) | ||
+ | print "Command status: "+str(response.status_code) | ||
+ | if response.status_code == 200: | ||
+ | |||
+ | open (<outputfile>, 'wb').write(response.content) | ||
+ | #with open ("./output.file", 'wb') as f: | ||
+ | # for chunk in response.iter_content(chunk_size=1024): | ||
+ | # f.write(chunk) | ||
+ | |||
+ | response = enm_session.post(rest_url+"/logout", verify=False) | ||
+ | return() | ||
+ | |||
+ | main() | ||
+ | </syntaxhighlight> |
Revision as of 14:00, 17 October 2018
REST, REpresentational State Transfer
- Transports JSON-formatted data over HTTP
- Stateless as the server does not hold client context (history). Pre: simple, Con: sometimes more requests needed.
Example code, fetching a file:
#!/usr/bin/env python
import requests
import json
import sys
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
rest_host = "<servername>"
rest_url = "https://"+rest_host
command_url = "<filepath"
post_headers = '{"Content-Type":"application/json"}'
def main():
rest_session = requests.Session()
response = rest_session.post(rest_url+"/login",
data={"USERNAME":<user>,"PASSWORD":<password>"},
verify=False)
print "login status: "+str(response.status_code)
response = rest_session.get(rest_url+command_url,verify=False,stream=True)
print "Command status: "+str(response.status_code)
if response.status_code == 200:
open (<outputfile>, 'wb').write(response.content)
#with open ("./output.file", 'wb') as f:
# for chunk in response.iter_content(chunk_size=1024):
# f.write(chunk)
response = enm_session.post(rest_url+"/logout", verify=False)
return()
main()