How to use Requests (Python Library)

TL;DR

--Requests is Python's ** modern ** HTTP library. --You can make a GET request with requests.get ('URL'). --You can get the response body in text format by setting .text to the response.

What are Requests

Python HTTP library. Python has a library called urllib2, but as the official website explains Requests is an Apache2 Licensed HTTP library, written in Python, for human beings., It is easy for humans to code.

Introduction

pip install requests

How to use

Library import

import requests

request

There are one-to-one correspondence methods for various HTTP methods.

# GET
requests.get('URL')
# POST
requests.post('URL')
# PUT
requests.put('URL')
# DELETE
requests.delete('URL')
#Get header
requests.head('URL')

Parameter assignment

Add params = to the argument of the request method with hash of the parameter to be added.

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('URL', params=payload)

Custom header

When specifying a UA in a GET request

>>> headers = {'User-Agent': 'Sample Header'}
>>> requests.get('URL', headers=headers)

When adding data to HTTP headers with a POST request

>>> payload = {'send': 'data'}
>>> requests.post('URL', data=json.dumps(payload))

Contents of the response

text

Get the returned response body in text format. The request is automatically decoded into unicode.

>>> r = requests.get('http://yahoo.com/')
>>> r.text
'<!DOCTYPE html>\n<html lang="en-US" class="dev-desktop uni-purple-border  bkt901 https  uni-dark-purple sasb-space" style="">\n<!-- m2 template  -->\n<head>\n    <meta http-equiv="Content-Type" ...

encoding

Get encoding information

content

Get the response body in binary format.

>>> import requests
>>> r = requests.get('http://www.fnal.gov/faw/designstandards/filesfordownload/FermiLogo_blue.gif')
>>> r.content

Processing for each response

image

Use PIL's Image module.

>>> from PIL import Image
>>> from StringIO import StringIO
>>> r = requests.get('http://www.fnal.gov/faw/designstandards/filesfordownload/FermiLogo_blue.gif')
>>> i = Image.open(StringIO(r.content))

JSON

>>> requests.get('http://ci.nii.ac.jp/ncid/BB08796640.json').json()
{'@context': {'foaf': 'http://xmlns.com/foaf/0.1/', 'prism': 'http://prismstandard.org/namespaces/basic/2.0/', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'owl': 'http://www.w3.org/2002/07/ ...

sample

requests_use.py


# -*- coding: utf-8 -*-

import doctest
import requests

def sample(query):
    """ requests sample that use qiita search api
    >>> 'title' in sample('python')
    True
    >>> 'totle' in sample('python')
    False
    """
    q = {'q':  query}
    r = requests.get('https://qiita.com/api/v1/search', params=q)
    return list(r.json()[0].keys())

if __name__ == "__main__":
    doctest.testmod()

References

team information: (housyu, 3cdc8fdc466a6315c030)

Recommended Posts

How to use Requests (Python Library)
python3: How to use bottle (2)
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
How to use the C library in Python
How to use Python Image Library in python3 series
Python: How to use async with
[Python] How to use Pandas Series
How to use SQLite in Python
[Python] How to use the graph creation library Altair
[Python] How to import the library
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
[Python] How to use Typetalk API
[python] How to use the library Matplotlib for drawing graphs
[Python] Summary of how to use pandas
[Introduction to Python] How to use class in Python?
How to install and use pandas_datareader [Python]
[python] How to use __command__, function explanation
[Python] How to use import sys sys.argv
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
[Python2.7] Summary of how to use unittest
python: How to use locals () and globals ()
How to use __slots__ in Python class
How to use "deque" for Python data
How to use Python zip and enumerate
[Python] Understand how to use recursive functions
Summary of how to use Python list
How to use regular expressions in Python
[Python2.7] Summary of how to use subprocess
How to use is and == in Python
[Blender x Python] How to use modifiers
[Question] How to use plot_surface of python
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to install Python
How to use Pandas 2
How to use Virtualenv
How to use pytest_report_header
How to install python
How to use partial
How to use Bio.Phylo