python_wiki:requests

This is an old revision of the document!


Requests

General Information

The requests library is a http library that allows you to interact with web servers via Python.

Checklist

  • Python 2 or 3

Install

Requests can be installed via pip

pip install requests

Import

import requests

Using Requests

Requests supports the following http request types.

my_site = "http://www.mysite.org/"
 
# GET
response = request.get(my_site)
 
# POST
response = request.post(my_site)
 
# PUT
response = request.put(my_site)
 
# DELETE
response = request.delete(my_site)
 
# HEAD
response = request.head(my_site)
 
# OPTIONS
response = request.options(my_site)

Using the GET request and handling the response data.


Example: Retrieve the latest XKCD Comic Info ( More Info: https://xkcd.com/json.html)

#!/usr/bin/python3                                                                         
 
import requests
 
# XKCD Current Comic JSON API
my_site = "https://xkcd.com/info.0.json"
 
# Retrieve using GET
print("Sending GET to: " + my_site)
response = requests.get(my_site)
 
# Extract the JSON object from the response
data = response.json()
 
# Show http status code on GET
print("Status code is:" + str(response.status_code))
 
# Show Certain fields from the JSON object
print("\n-- The Current XKCD Comic --")
print("Comic Title: " + data['title'])
print("Comic Text: " + data['alt'])
print("Comic Date: " + data['year'] + "-" + data['month'] + "-" + data['day'])


Output from above example

Sending GET to: https://xkcd.com/info.0.json
Status code is:200
 
-- The Current XKCD Comic --
Comic Title: Complex Numbers
Comic Text: I'm trying to prove that mathematics forms a meta-abelian group, which would finally confirm my suspicions that algebreic geometry and geometric algebra are the same thing.
Comic Date: 2018-8-3

POST

Send data in a POST request.


  • python_wiki/requests.1533500114.txt.gz
  • Last modified: 2019/05/25 23:50
  • (external edit)