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

如何将其他语言的API令牌请求转为Python requests实现?

如何将非Python API示例转换为requests实现

问题背景

我是requests库的新手,通常API服务的开发者指南都会包含Python相关内容,但这次我遇到了一个未提供Python示例的API服务,仅给出了PHP、Java和C#的示例。我的问题是,如何将这些API说明转换为Python requests的实现方式。

官方提供的示例

PHP示例

<?php
   $username = 'USERNAME';
   $password = 'PASSWORD';
   $FIM_endpoint = 'https://fim.api.ENV.fleetmatics.com/token';

   //Call method and set variable to authorization string
   $token = get_token($FIM_endpoint, $username, $password);

   echo $token;

   function get_token($url, $username, $password)
   {
      //Create necessary headers for REST call
      $headers = array();
      $headers[] = make_authorization_header($username, $password);    //Send to function to Base64 encode
      $headers[] = 'Accept: text/plain';                               //Authorization token comes back as plain text
   
      $session = curl_init($url);                             //Initialize transfer with URL
      curl_setopt($session, CURLOPT_HEADER, false);           //Exclude header info in response
      curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    //Return transfer as a string of the return value of curl_exec()
      curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    //Pass in headers
    
      //Execute transfer of $session
      $response = curl_exec($session); 

      //Get http code outcome of the #session transfer    
      $http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);

      //Measure false response/error          
      if($response === false)
      {
         echo 'Error: '. curl_error($session);
      }
      
      //ALWAYS close transfer connection        
      curl_close($session);

      //Evaluate variable for non 200(OK) http code       
      if($http_code !== 200)
      {
         echo 'Error: Http Status Code returned '.$http_code;
      }    
   
      return $response;    
   }
   
   function make_authorization_header($username, $password)
   {
      //Base64 encode username:password; note: the ':' must be present between them   
      $encodedString = base64_encode($username.':'.$password);
      
      //Return concatenated Authorization string      
      return 'Authorization: Basic '.$encodedString;
   }
?>

Java示例

public class Program{
  public static void main(String[] args){
    
    // Set local variables
    String username = "username";
    String password = "password";
    String getTokenUri = "https://fim.api.ENV.fleetmatics.com/token";

    // Pass variables to create a new TokenGenerator object    
    TokenGenerator token = new TokenGenerator(username, password, getTokenUri);
    
    // Display auth string      
    System.out.println(token.GetAuthString());
  }
}

C#示例

using System; // Note: This can be omitted if Console.WriteLine is not used

namespace Rest_Token_Example
{
    class Program
    {
        static void Main()
        {
            // Set local variables 
            string username = "username";
            string password = "password";
            string getTokenURI = "https://fim.api.ENV.fleetmatics.com/token";

            // Pass variables to create a new TokenGenerator object
            var token = new TokenGenerator(username, password, getTokenURI);

            // Display token string
            Console.WriteLine(token.AuthString);
        }
    }
}

我的错误尝试

authUser = "username"
authPass = "password"
authoURL = "https://fim.api.ENV.fleetmatics.com/tokens"

response = requests.get(authoURL, headers={authUser, authPass})

print (response)
#<Response [404]>

我还尝试将headers替换为auth的多种格式,但都没有效果。


解决方案

错误分析

  1. 端点错误:你写的authoURL是/tokens,但官方示例里的端点是/token,多了一个s,这是导致404的直接原因。
  2. 请求头格式错误:headers={authUser, authPass}是无效的字典格式,请求头需要键值对结构,比如{"Key": "Value"}。
  3. Basic Auth实现错误:官方示例使用HTTP Basic认证,需要将username:password进行Base64编码后放在Authorization头里,或者直接用requests的内置参数简化操作。

正确实现方式

方式1:使用requests内置的auth参数(推荐)

requests库直接支持Basic Auth,传入auth=(username, password)即可自动处理编码和头的设置:

import requests

username = "username"
password = "password"
token_url = "https://fim.api.ENV.fleetmatics.com/token"

# 设置请求头,指定接受纯文本响应
headers = {
    "Accept": "text/plain"
}

response = requests.get(token_url, auth=(username, password), headers=headers)

# 处理响应
if response.status_code == 200:
    token = response.text
    print("获取到的Token:", token)
else:
    print(f"请求失败,状态码: {response.status_code}")
    print("错误信息:", response.text)

方式2:手动构造Authorization头

如果你想完全复刻PHP示例的逻辑,可以手动编码用户名密码:

import requests
import base64

username = "username"
password = "password"
token_url = "https://fim.api.ENV.fleetmatics.com/token"

# 构造Basic Auth字符串
auth_str = f"{username}:{password}"
encoded_auth = base64.b64encode(auth_str.encode("utf-8")).decode("utf-8")

headers = {
    "Authorization": f"Basic {encoded_auth}",
    "Accept": "text/plain"
}

response = requests.get(token_url, headers=headers)

# 处理响应
if response.status_code == 200:
    token = response.text
    print("获取到的Token:", token)
else:
    print(f"请求失败,状态码: {response.status_code}")
    print("错误信息:", response.text)

关键注意点

  • 确保端点URL正确:是/token而不是/tokens
  • 必须设置Accept: text/plain头,和PHP示例保持一致,确保API返回纯文本格式的Token
  • 处理非200状态码的情况,方便排查错误

内容的提问来源于stack exchange,提问作者BSIncorporated

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:00:00