如何在Python中为API调用链接添加变量(以嵌入ID参数为例)
Hey there! Let's get that ID variable (set to 156) properly inserted into your API URL so you can make a valid request. Here are three straightforward methods, each with their own perks:
1. Use F-Strings (Recommended for Python 3.6+)
F-strings are the cleanest and most readable way to inject variables into strings these days. Just wrap your variable in {} directly inside the string:
import requests # Define your ID variable target_id = 156 # Build the URL with the embedded ID url1 = f'https://comtrade.un.org/api/get?r={target_id}&px=HS&ps=2020&p=0&rg=1&cc=total' # Execute the request and verify the generated URL response1 = requests.get(url1) print(response1.url)
Running this will print the full URL with 156 replacing the <id> placeholder—perfect for confirming everything's set up right.
2. str.format() Method (For Older Python Versions)
If you're working with a Python version before 3.6, the format() method is a reliable alternative:
import requests target_id = 156 url1 = 'https://comtrade.un.org/api/get?r={}&px=HS&ps=2020&p=0&rg=1&cc=total'.format(target_id) response1 = requests.get(url1) print(response1.url)
This works the same way in practice—just uses a different syntax to slot in the variable.
3. Use requests' Built-in Params Dictionary (Most Robust)
For a more maintainable approach (especially if you ever need to adjust parameters later), let requests handle the URL building for you. Pass all your parameters as a dictionary:
import requests target_id = 156 # Define all API parameters in a dictionary api_params = { 'r': target_id, 'px': 'HS', 'ps': 2020, 'p': 0, 'rg': 1, 'cc': 'total' } # Send the request with params instead of a pre-built URL response1 = requests.get('https://comtrade.un.org/api/get', params=api_params) print(response1.url)
This method automatically handles URL encoding (if needed) and keeps your parameters organized—super handy if your API call gets more complex down the line.
Whichever method you pick, checking response1.url is a great way to confirm the final request URL is exactly what you want.
内容的提问来源于stack exchange,提问作者Alvaromasa1

