Python API新手请求:获取AccessToken并拉取第三方数据代码协助
Hey there! I know getting started with a new API can feel tricky, especially when your first attempts don't pan out. Let's break this down into simple, working Python code using the requests library—we'll handle the token generation first, then fetch the data you need.
First, we need to send a POST request to the login endpoint with your credentials to get a valid TokenID. Here's how to do that:
import requests import json # Your account credentials USER_ID = "trial" PASSWORD = "aaw3r5lL" def get_auth_token(): login_url = "https://api.Asw.com/api/auth.json" # Using JSON for easier parsing payload = { "uid": USER_ID, "password": PASSWORD } try: # Send POST request to the login endpoint response = requests.post(login_url, data=payload) response.raise_for_status() # Catch HTTP errors like invalid credentials # Extract TokenID from the JSON response token_data = response.json() token_id = token_data.get("TokenID") # Adjust the key if the response uses a different name if not token_id: raise ValueError("TokenID not found in the login response") print(f"Successfully retrieved token: {token_id}") return token_id except requests.exceptions.RequestException as e: print(f"Login failed: {e}") return None
A quick breakdown:
- We use the
.jsonendpoint since parsing JSON is more straightforward in Python than XML. - The
payloadincludes your requireduidandpassword, sent as form data (which matches the API's implicit content type for login). response.raise_for_status()will alert you immediately if there's an issue like wrong credentials (401) or server errors (500).
Once you have a valid TokenID, we can send the data request. Remember to include the authorization header and format the point parameter correctly:
def get_weather_data(token_id, points): data_url = "https://api.Asw.com/api/v1/hires-weather-on-track.json" headers = { "Authorization": f"AswWebApi {token_id}" } # Convert the points list to a JSON string (required for the API parameter) payload = { "point": json.dumps(points) } try: response = requests.post(data_url, headers=headers, data=payload) response.raise_for_status() # Parse and return the retrieved data weather_data = response.json() print("Successfully fetched weather/ship track data") return weather_data except requests.exceptions.RequestException as e: print(f"Data request failed: {e}") return None
Key notes here:
- The
Authorizationheader strictly follows the format specified:"AswWebApi " + TokenID—we use an f-string to insert the token cleanly. - Since the API expects
application/x-www-form-urlencodedcontent, we send thepointparameter as a form field, with the list of points converted to a JSON string usingjson.dumps().
Let's call these functions with an example list of points (replace this with your actual coordinates):
if __name__ == "__main__": # Get the auth token first token = get_auth_token() if token: # Example points (adjust to match the API's expected point format) example_points = [ {"lat": 31.2304, "lon": 121.4737}, {"lat": 30.2741, "lon": 120.1551} ] # Fetch the data weather_data = get_weather_data(token, example_points) if weather_data: # Do something with the data (print, save to file, etc.) print(json.dumps(weather_data, indent=2))
Extra Tips for Success
- Token Expiry: Since the token is valid for 24 hours, you can save it to a file (e.g.,
token.txt) to avoid re-logging every time. Just add logic to check if the token is expired (you'll get a 401 error) and re-login if needed. - XML Format: If you need XML instead of JSON, replace
.jsonwith.xmlin the URLs, and useresponse.textto get the raw XML (then parse it withxml.etree.ElementTree). - Debugging: If things still go wrong, add
print(response.text)after each request to see the raw API response—this helps spot issues like misnamed parameters or missing fields.
内容的提问来源于stack exchange,提问作者user8231331

