In userequests
Librarypost
When the method,params
Parameters of types are usually used to pass as query strings in URLs. This is withdata
orjson
The parameters are different, the latter is placed in the request body. Here is a detailed introduction to how to use itpost
Pass when methodparams
parameter.
Use params parameters
params
The parameter accepts a dictionary or sequence of key-value pairs that will be encoded and attached to the requested URL as a query string.
Sample code
import requests # Define the target URLurl = '/post' # Define the parameters to be passedparams = { 'key1': 'value1', 'key2': 'value2' } # Send POST request and pass params parametersresponse = (url, params=params) # Print the response status codeprint('Status Code:', response.status_code) # Print the actual requested URL (including query parameters)print('Request URL:', ) # Print response content (usually in JSON format)print('Response Body:', ())
Output example
Status Code: 200
Request URL: /post?key1=value1&key2=value2
Response Body: {'args': {'key1': 'value1', 'key2': 'value2'}, 'data': '', 'files': {}, 'form': {}, 'headers': {...}, 'json': None, 'method': 'POST', 'origin': '...', 'url': '/post?key1=value1&key2=value2'}
In the example above,params
The parameter was successfully added to the requested URL as a query string?key1=value1&key2=value2
。
The difference between params and data and json
• params
: Used to append data as a query string to the URL. Suitable for GET requests, but can also be used with POST requests to put data in the URL.
• data
: Used to place data in the request body, usually used to send form data. Suitable for POST, PUT and other request methods.
• json
: Used to place data in JSON format in the request body. Applicable to API interfaces that require sending JSON data.
Example comparison
useparams
response = (url, params=params) # Request URL: /post?key1=value1&key2=value2# Request body: null
usedata
data = { 'key1': 'value1', 'key2': 'value2' } response = (url, data=data) # Request URL: /post# Request body: key1=value1&key2=value2 (Form encoding)
usejson
json_data = { 'key1': 'value1', 'key2': 'value2' } response = (url, json=json_data) # Request URL: /post# Request body: {"key1": "value1", "key2": "value2"} (JSONFormat)
Things to note
-
URL length limit: Although it can be used
params
Attach data to a URL, but pay attention to the browser and server limits on URL length. For large amounts of data, it is recommended to usedata
orjson
method. -
Coding issues:
requests
The library automatically handles URL encoding, so there is no need to manually encode parameters. - Security: Sensitive information is not recommended to be passed through the URL's query string, as this information may be recorded in the server log or browser history.
Advanced Usage
Pass a list or tuple as parameter value
Sometimes, a parameter may need to pass multiple values. This can be done by passing lists or tuples.
params = { 'key1': 'value1', 'key2': ['value2', 'value3'] } response = (url, params=params) print() # Output: /post?key1=value1&key2=value2&key2=value3
Use params in combination with other parameters
You can also use it at the same timeparams
、data
andheaders
etc.
params = {'search': 'robotframework'} data = {'username': 'user', 'password': 'pass'} headers = {'Authorization': 'Bearer YOUR_TOKEN'} response = (url, params=params, data=data, headers=headers) print() # Contains query parametersprint() # Contains form dataprint() # Include request header
Complete example
Here is a more complete example showing how to use it in real-life applicationsparams
Parameters send a POST request and process the response.
import requests def post_with_params(): url = '/post' params = { 'api_key': 'YOUR_API_KEY', 'token': 'SESSION_TOKEN' } data = { 'username': 'testuser', 'action': 'login' } try: response = (url, params=params, data=data, timeout=10) response.raise_for_status() # Check whether the request is successful result = () print('The request was successful! ') print('API Response:', result) except as http_err: print(f'HTTPAn error occurred: {http_err}') except Exception as err: print(f'其他An error occurred: {err}') if __name__ == '__main__': post_with_params()
In this example:
• useparams
Passedapi_key
andtoken
As query parameters.
• usedata
Passed the username and action required for login.
• Added exception handling to ensure that errors can be caught and reported when requests fail.
Summarize
• params
The parameter is used to append data as a query string to the requested URL.
• Although mainly used for GET requests, it can also be used with POST requests.
• For large amounts of data or sensitive information, it is recommended to use itdata
orjson
method.
• requests
The library automatically handles the encoding of parameters, simplifying the request construction process.
Hope this information helps you better understand and use itrequests
In the libraryparams
parameter!
This is the article about how to transfer params-type parameters from the requests library post method. For more related requests library post method, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!