Python for Delphi (Python4Delphi , P4D) with Requests library allow you to execute Http requests in Python GUI for Windows. Python4Delphi is a free tool that can run Python scripts, work with new Python types and modules in Delphi. In this post, we will learn at how to run Requests library in Python for Delphi.
Build your own Python GUI apps for Windows with Delphi and C++Builder and Python4Delphi using various Python libraries. Open and run project Demo1, then select Python script that you want execute in Python for Delphi. Use text fields for inserting Python script and for viewing results. Click Execute button for running Python script. Go to GitHub and download Demo1 source.
1 2 3 4 |
procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; |
Requests is a simple Python library that allows you to execute standard HTTP requests. Using this library, you can pass parameters to requests, add headers, receive and process responses, execute authenticated requests. Let’s look at some examples.
Table of Contents
Make GET Request
It is very easy to call GET request. Just use method get() and pass URL to this method. From response object you can get a lot of useful information. This example shows how to get content, status and list of response headers. You also can get other properties.
1 2 3 4 5 |
import requests r = requests.get('https://example.com') print(r.text) print(r.headers) print(r.status_code) |
POST Request with payload and timeout
With Requests library, you can perform post requests by calling post() method. It is also possible to pass input data to the parameter payload. Different types of input data are possible. For example, dictionaries, tuples, lists
1 2 3 4 5 6 7 8 9 10 11 12 |
import requests payload1 = {'key1': 'value1', 'key2': 'value2'} r = requests.post("https://httpbin.org/post", data=payload1) print(r.text) payload2 = [('key1', 'value1'), ('key1', 'value2')] r1 = requests.post('https://httpbin.org/post', data=payload2) print(r1.text) payload3 = {'key1': ['value1', 'value2']} r2 = requests.post('https://httpbin.org/post', data=payload3) print(r2.text) |
Authenticated Request
In this example we will take a look at how to execute authenticated requests. It is very easy, just pass the username and the password in the auth parameter. If authorization is successful, then we will receive a response status code 200, otherwise there should be non-authorization error 404.
1 2 3 4 |
import requests from getpass import getpass r=requests.get('https://test.org', auth=('username', getpass())) print(r.status_code) |
Check out the Requests library for Python a use it in your own projects. Check out Python4Delphi which can build Python GUIs for Windows using Delphi.