|
| 1 | +## Request Module |
| 2 | +### Introduction |
| 3 | +``` |
| 4 | +Requests will allow you to send HTTP/1.1 requests using Python. With it, you can add content like headers, form data, multipart files, and parameters via simple Python libraries. It also allows you to access the response data of Python in the same way. |
| 5 | +``` |
| 6 | +### Make a GET request |
| 7 | +```python |
| 8 | +import requests |
| 9 | +URL = "http://maps.googleapis.com/maps/api/geocode/json" |
| 10 | +location = "delhi technological university" |
| 11 | +PARAMS = {'address':location} |
| 12 | +r = requests.get(url = URL, params = PARAMS) |
| 13 | +data = r.json() |
| 14 | + latitude = data['results'][0]['geometry']['location']['lat'] |
| 15 | +longitude = data['results'][0]['geometry']['location']['lng'] |
| 16 | +formatted_address = data['results'][0]['formatted_address'] |
| 17 | +print("Latitude:%s\nLongitude:%s\nFormatted Address:%s" |
| 18 | + %(latitude, longitude,formatted_address)) |
| 19 | +``` |
| 20 | +Output: |
| 21 | +``` |
| 22 | +Latitude:28.7499867 |
| 23 | +Longitude:77.1183137 |
| 24 | +Formatted Address:Delhi Technological University, Shahbad Daulatpur Village, Rohini, Delhi, 110042, India |
| 25 | +``` |
| 26 | +### Make a POST request |
| 27 | +```python |
| 28 | +import requests |
| 29 | + API_ENDPOINT = "http://pastebin.com/api/api_post.php" |
| 30 | +API_KEY = "XXXXXXXXXXXXXXXXX" |
| 31 | +source_code = ''' |
| 32 | +print("Hello, world!") |
| 33 | +a = 1 |
| 34 | +b = 2 |
| 35 | +print(a + b) |
| 36 | +''' |
| 37 | +data = {'api_dev_key':API_KEY, |
| 38 | + 'api_option':'paste', |
| 39 | + 'api_paste_code':source_code, |
| 40 | + 'api_paste_format':'python'} |
| 41 | + |
| 42 | +r = requests.post(url = API_ENDPOINT, data = data) |
| 43 | +pastebin_url = r.text |
| 44 | +print("The pastebin URL is:%s"%pastebin_url) |
| 45 | +``` |
| 46 | +Output: |
| 47 | +```python |
| 48 | +This example explains how to paste your source_code to pastebin.com by sending POST request to the PASTEBIN API.You will need to generate an API key here http://pastebin.com/signup |
| 49 | + data = {'api_dev_key':API_KEY, |
| 50 | + 'api_option':'paste', |
| 51 | + 'api_paste_code':source_code, |
| 52 | + 'api_paste_format':'python'} |
| 53 | +Here again, we will need to pass some data to API server. We store this data as a dictionary. |
| 54 | + r = requests.post(url = API_ENDPOINT, data = data) |
| 55 | +Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary. |
| 56 | + pastebin_url = r.text |
| 57 | +In response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text . |
| 58 | +``` |
| 59 | + |
0 commit comments