DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

Here you will see how to use this library to send simple
HTTP requests in Python as way to illustrate its ease of
use.


You can use Requests with Python versions 2.7 and 3.x.
Requests is an external module, so it needs to be
installed before you can use it. Example 7-11 shows the
command you use to install the Requests package for
Python.


Example 7-11 Installing the Requests Package for
Python


$ pip3 install requests

To add HTTP headers to a request, you can simply pass
them in a Python dict to the headers parameter.
Similarly, you can send your own cookies to a server by
using a dict passed to the cookies parameter. Example 7-
12 shows a simple Python script that uses the Requests
library and does a GET request to the Postman Echo
server.


Example 7-12 Simple HTTP GET Using Python
Requests


Click here to view code image


import requests
url = "https://postman-echo.com/get"
querystring = {"test":"123"}
headers = {}
response = requests.request("GET", url,
headers=headers, params=querystring)
print(response.text)

Example 7-13 shows a simple Python script that uses the
Requests library and does a POST request to the
Postman Echo server. Notice that the headers field is
populated with the content type and a new field call

Free download pdf