The 1 Python package is an HTTP library created by Kenneth Reitz. It's a very well known package in the Python community for making HTTP requests easy to create and call. This tutorial will cover the basics that you will need to know and will want to know when making HTTP requests in Python. Show
Learning how to send HTTP requests allows you to query websites and API's for data or even a webpage so you can scrape data out with something like Beatifulsoup. InstallationTo install the requests module, first make sure you have pip setup. If not, follow my tutorial on setting up pip. After making sure pip is working, execute 2. When this is successful, open Python IDLE and execute 3; if no errors occur, the requests module has been installed successfully.Making a Simple RequestJust like your browser does, you can request a web page using Python. Get the URL of a website and use the following code to download the content of the page.
When executing this, a lot of text should be printed. This is the content returned by the site requested, in the case of using the URL demonstrated above, the content will be HTML that renders my blog feed. In this example, I have called 4 passing my URL to be fetched. This function then returns a 5 object. Using the 6 attribute, I can look at the data that was returned by the URL I called.
Attributes You Should Know AboutThe 7 object that was returned in the example above contains many useful attributes. Here are some ones you should know about:
To get the value of these attributes, use them as I did in the previous code example. .json()If a site returns a JSON response, you can call 4 on the 7 object to convert the JSON object in the response to a Python dictionary.
This saves the effort on deserializing the .text value using the . Downloading an Image and Other FilesJust like downloading a web page, you can also download other files like images or videos. Simply find the URL of the image/other file (make sure it is the URL of the file, not the URL of the page it's on) and use it like before; but this time put the content into a file.
If you expect the file to be large (or just want to use a stream), you can use a stream to write to the output file as you receive the data. This means as the data comes in, it is written to the output file so the data does not have to sit in memory.
Different MethodsWhen making a request to a URL/URI, different 'methods' can be used. These tell the server what sort of action you want to perform. HTTP defines actions like GET, POST, PUT, DELETE and many others. To use these different methods, simply replace the 6 with 7/ 8/ 9 or whatever method you are using. For example, if I wanted to delete a record in a REST API, I could use:
Parameters in URLsInstead of constructing a URL to add parameters to it, the requests module offers a method to add them automatically for you. Simply create your key-value pairs in a Python dictionary and then pass this to the 0 argument in the request method. For example:
To show that the parameters were added to the url, we can verify it using a PreparedRequest.
Sending Data in HTTP BodyWhen making calls to endpoints that require data in the body, we can use form-encoded, JSON or raw bodies. Form Encoded BodyIn cases where you want to send some form-encoded data (like a HTML form would submit), we can pass key-value pairs as we used above to the 1 parameter. The dictionary of your data will be form-encoded when the request is made. For example:
JSON BodyToday, JSON bodies are becoming more popular over form-encoded key-value pairs; this is due to how much more compact JSON is over XML (XML and JSON are typically used to carry larger payloads). Fortunately, JSON bodies are as easy to create in the request module as form-encoded are. Instead of passing your dictionary to the 1 parameter, pass it to 3. When the request is made, the 4 header will automatically be set to 5 to tell the server that this is a JSON request.
Raw BodyIn the cases where you want to specify exactly what is in the body manually, simply provide the string to the 6 parameter. For example:
Custom headersPreviously I discussed that the 4 header will automatically be set to 5 when passing data to 3. We can set headers manually is a very similar way to how we have been sending data. Once again, create the header key-value pairs in a Python dictionary and then pass them to the 0 parameter. 0This is Only The BasicsPlease know that these are only the basics of the requests library and there is a lot more to offer from this library; this tutorial however, should help you understand what you need to do to request and send data. If you want to read up more on this library, Google is full of answers but the docs at requests.readthedocs.io is great for reference material. I Don't Have s Server, How Can I Test These?webhook.site is an amazing place to test requests. Simply going to the page will create a new webhook for you to use - copy the unique URL at the top of the page (not the URL address bar). Now whenever you make a request to that URL, you will be able to see the content of the request you made. How do you turn something into a dictionary in Python?You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.
How to convert a JSON to dictionary in Python?This function is used to parse the JSON string.. Syntax: json.load(file_name). Parameter: It takes JSON file as the parameter.. Return type: It returns the python dictionary object.. How to convert a string into dictionary in Python?Method #1 : Using json.loads()
This task can easily be performed using the inbuilt function of loads of json library of python which converts the string of valid dictionary into json form, dictionary in Python.
How do I extract data from a Python request?In this example, we would be connecting to an Open source COVID API just to extract and parse the json information in an customized manner.. Connect to an API. ... . Get the data from API. ... . Parse the data into JSON format. ... . Extract the data and print it.. |