You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为API调用链接添加变量(以嵌入ID参数为例)

How to Embed Your ID Variable into the Comtrade API Request with Python

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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:57:48