# 以OpenWeatherMap API為例
api_key = "your_api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = "New York"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

response = requests.get(complete_url)
data = response.json()

if data["cod"] != "404":
main = data["main"]
temperature = main["temp"]
pressure = main["pressure"]
humidity = main["humidity"]
weather_description = data["weather"][0]["description"]

print(f"Temperature: {temperature}")
print(f"Pressure: {pressure}")
print(f"Humidity: {humidity}")
print(f"Weather Description: {weather_description}")
else:
print("City Not Found")

這段代碼展示了如何使用OpenWeatherMap API獲取紐約市的天氣信息。

4. 云服務API的類型

5. Amazon S3 API 示例

Amazon S3是一個對象存儲服務,可以用來存儲和檢索任意數量的數據。要使用S3 API,你需要安裝boto3庫。

pip install boto3
import boto3

s3 = boto3.client('s3',
aws_access_key_id='YOUR_ACCESS_KEY',
aws_secret_access_key='YOUR_SECRET_KEY')

bucket_name = 'your-bucket-name'
file_path = '/path/to/local/file'
key = 'path/in/s3/bucket'

# 上傳文件
s3.upload_file(file_path, bucket_name, key)

# 下載文件
s3.download_file(bucket_name, key, file_path)

# 列出所有文件
response = s3.list_objects_v2(Bucket=bucket_name)
for content in response.get('Contents', []):
print(content.get('Key'))

6. AWS Lambda API 示例

AWS Lambda是一種無服務器計算服務,可以在沒有服務器的情況下運行代碼。首先,你需要創建一個Lambda函數并通過API觸發它。

import boto3

lambda_client = boto3.client('lambda',
aws_access_key_id='YOUR_ACCESS_KEY',
aws_secret_access_key='YOUR_SECRET_KEY',
region_name='us-east-1')

function_name = 'your-function-name'
payload = {"key1": "value1", "key2": "value2"}

response = lambda_client.invoke(FunctionName=function_name,
InvocationType='RequestResponse',
Payload=json.dumps(payload))

print(response['Payload'].read())

這段代碼展示了如何調用一個Lambda函數并傳遞參數。

7. Google Cloud Firestore API 示例

Google Cloud Firestore是一個靈活的NoSQL數據庫,用于存儲和同步數據。首先,你需要安裝firebase-admin庫。

pip install firebase-admin
import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate('path/to/serviceAccount.json')
firebase_admin.initialize_app(cred)

db = firestore.client()
doc_ref = db.collection(u'users').document(u'alovelace')

# 寫入數據
doc_ref.set({
u'first': u'Ada',
u'last': u'Lovelace',
u'born': 1815
})

# 讀取數據
doc = doc_ref.get()
print(f'Document data: {doc.to_dict()}')

這段代碼展示了如何向Firestore數據庫中寫入和讀取數據。

8. Microsoft Azure Cognitive Services API 示例

Azure Cognitive Services提供了多種智能API,如計算機視覺、語音識別等。這里以計算機視覺API為例。

import requests

subscription_key = "your_subscription_key"
endpoint = "https://your-endpoint.cognitiveservices.azure.com/"
analyze_url = endpoint + "vision/v3.2/analyze"

image_url = "https://example.com/image.jpg"
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
params = {'visualFeatures': 'Categories,Description,Color'}
data = {'url': image_url}

response = requests.post(analyze_url, headers=headers, params=params, json=data)
analysis = response.json()

print(analysis)

19. 實戰案例:綜合天氣應用與通知系統

假設我們要開發一個綜合天氣應用,該應用不僅可以顯示天氣信息,還可以在特定條件下發送通知給用戶。具體功能如下:

1. 用戶輸入城市名,顯示該城市的天氣信息。2. 如果天氣狀況不佳(如暴雨、大風等),自動發送短信通知給用戶。

首先,注冊OpenWeatherMap賬戶并獲取API密鑰。同時,注冊Twilio賬戶并獲取API密鑰。

接下來,編寫如下代碼:

import requests
from twilio.rest import Client

def get_weather(city):
api_key = "your_api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city

response = requests.get(complete_url)
data = response.json()

if data["cod"] != "404":
main = data["main"]
temperature = main["temp"]
pressure = main["pressure"]
humidity = main["humidity"]
weather_description = data["weather"][0]["description"]

return {
"temperature": temperature,
"pressure": pressure,
"humidity": humidity,
"description": weather_description
}
else:
return None

def send_sms(message, recipient_phone_number):
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

message = client.messages.create(
body=message,
from_='+1234567890', # Your Twilio phone number
to=recipient_phone_number
)

print(f'SMS sent: {message.sid}')

city = input("Enter city name: ")
weather_data = get_weather(city)

if weather_data is not None:
print(f"Weather in {city}:")
print(f"Temperature: {weather_data['temperature']}")
print(f"Pressure: {weather_data['pressure']}")
print(f"Humidity: {weather_data['humidity']}")
print(f"Description: {weather_data['description']}")

if "rain" in weather_data['description']:
recipient_phone_number = '+1234567890' # Recipient's phone number
message = f"Heavy rain warning in {city}. Please take precautions."
send_sms(message, recipient_phone_number)
elif weather_data is None:
print("City Not Found")

用戶運行程序后,輸入城市名,即可看到該城市的天氣情況。如果天氣狀況不佳(如暴雨),程序會自動發送短信通知給用戶。

總結

本文介紹了云服務API的概念及其重要性,并通過多個實際示例展示了如何使用不同云服務商提供的API實現從存儲到計算再到AI等多種功能。最后,通過一個綜合實戰案例,展示了如何結合OpenWeatherMap API和Twilio API來構建一個具備天氣預報和通知功能的應用。這些示例為開發者提供了實用的參考指南。

本文章轉載微信公眾號@小白PythonAI編程

上一篇:

python機器人Agent編程——實現一個本地大模型和爬蟲結合的手機號歸屬地天氣查詢Agent

下一篇:

使用gin搭建api后臺系統之cookie與session
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費