SoFunction
Updated on 2024-11-18

How python calls a remote interface

In python we can use the requests module to call remote interfaces.

I: Install the requests module

pip install requests

Second: using the requests module to implement the get method to call the remote interface

The get method of the requests module is used to invoke the remote interface.

()

The common parameters of the get method are url, params and headers.

  • url: the address of the remote interface
  • params means get parameters
  • headers represents the information of the headers parameter of the get parameter.

A simple implementation of the get method of calling the remote interface using the requests module is as follows

# -*- coding: utf-8 -*-
import requests
import ast
# interface address
url = 'XXX'
#get passes a parameter
data = {'type':'0'}
#headers information
headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Bearer XXX'
}
#
r = (url, params=data, headers = headers)
# Status codes returned by the interface
print(r.status_code)
# The content of the string returned by the interface
content = 
# Convert strings to characters
content_list = ast.literal_eval(content)
print(content_list)
# Content returned by the interface in json format
print(())

According to the above, you can use the get method to call the remote interface.

Third: the use of requests module to achieve the post method to call the remote interface

The post method of the requests module is used to invoke the remote interface.

()

The common parameters of the post method are url, data and headers.

  • url: the address of the remote interface
  • data: represents the post parameter
  • headers: information about the headers parameter of the post parameter.

A simple implementation of the post method of calling the remote interface using the requests module is as follows.

# -*- coding: utf-8 -*-
import requests
import ast
# interface address
url = 'XXX'
#header information
headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Bearer XXX'
}
#post pass parameter
data = {
  'nickname': '111',
  'gender': 1,
  'city': 'ce',
  'avatar': '111'
}
r = (url, data=data,headers=headers)
# Status codes returned by the interface
print(r.status_code)
# The content of the string returned by the interface
content = 
# Convert strings to characters
content_list = ast.literal_eval(content)
print(content_list)
# Content returned by the interface in json format
print(())

The above is python how to call remote interface details, more information about python call remote interface please pay attention to my other related articles!