Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Integrating Skills with External APIs

Integrating Skills with External APIs

Skill scripts can call external HTTP APIs just like ordinary Python programs, connecting Claude's capabilities with third-party services.


Basic pattern for calling external APIs

Using the requests library to send HTTP requests is the most common way to call APIs in Skill scripts.

Example

File path: scripts/api_client.py

import

requests

import

json

import

sys

import

os

API keys are read from environment variables, not hardcoded in the script

API_KEY

=

os

.

environ

.

get

(

"MY_API_KEY"

,

""

)

BASE_URL

=

"https://api.example.com/v1"

def

call_api

(

endpoint:

str

,

payload:

dict

,

timeout:

int

=

30

)

dict

:

   

"""
    Generic API call wrapper

    Parameters:
        endpoint: API path, such as "/analyze"
        payload: request body (JSON)
        timeout: timeout in seconds, default 30

    Returns:
        Parsed JSON response, or a dictionary containing error
    """

   

if

not

API_KEY:

       

return

{

"error"

:

"API key not set, please set the environment variable MY_API_KEY"

}

    url

=

BASE_URL + endpoint

    headers

=

{

       

"Authorization"

: f

"Bearer {API_KEY}"

,

       

"Content-Type"

:  

"application/json"

   

}

   

try

:

        response

=

requests.

post

(

url

,

headers

=

headers

,

                                 json

=

payload

,

timeout

=

timeout

)

        response.

raise_for_status

(

)

 

Raise an exception on HTTP 4xx/5xx

       

return

response.

json

(

)

   

except

requests.

Timeout

:

       

return

{

"error"

: f

"Request timed out (exceeded {timeout} seconds)"

}

   

except

requests.

HTTPError

as

e:

       

return

{

"error"

: f

"HTTP error {e.response.status_code}: {e.response.text}"

}

   

except

requests.

ConnectionError

:

       

return

{

"error"

:

"Unable to connect to the API service, please check your network"

}

   

except

Exception

as

e:

       

return

{

"error"

:

str

(

e

)

}

Usage examples

if

name

==

"main"

:

    result

=

call_api

(

"/analyze"

,

{

       

"text"

:

"runoob is a well-known technology learning platform in China"

,

       

"lang"

:

"zh"

   

}

)

   

print

(

json.

dumps

(

result

,

ensure_ascii

=

False

,

indent

=

2

)

)


Secure management of API keys

API keys should not be written directly in script files; they should be passed via environment variables.

Example

Set environment variables before running the script

export

MY_API_KEY

=

"sk-xxxxxxxxxxxxxxxxxxxxxxxx"

python scripts

/

api_client.py

Or set them inline when executing the script

MY_API_KEY

=

"sk-xxxxxxxxxxxxxxxxxxxxxxxx"

python scripts

/

api_client.py

Tell users in SKILL.md that they need to configure the key:



## Prerequisites



This Skill requires an external API key. Please complete the following configuration before first use:



1. 在 [API 服务商网站] 注册并获取 API 密钥

2. Set environment variables in the terminal:

   ```bash

   export MY_API_KEY="你的密钥"

  1. To make it permanent, add the above command to ~/.bashrc or ~/.zshrc

If not configured, the Skill will prompt "API key not set" and exit.



> 

永远不要将 API 密钥提交到 Git 仓库。可以在 Skill 目录下创建 .gitignore 文件,将 .env 文件排除在版本控制之外。

--- ## Handling API Rate Limiting (Rate Limiting) 大多数 API 有请求频率限制。当批量调用 API 时,需要在请求间加入延迟。 ## 实例 # File path: scripts/rate_limited_client.py import time import requests class RateLimitedClient:     """带限速控制的 API 客户端"""     def __init__ ( self , base_url: str , api_key: str ,                  requests_per_minute: int = 60 ) :         self . base_url     = base_url         self . api_key     = api_key         self . min_interval = 60.0 / requests_per_minute   # Minimum interval between requests (seconds)         self . last_request = 0.0     def _wait_if_needed ( self ) :         """若距上次请求时间不足,等待剩余时间"""         elapsed = time . time ( ) - self . last_request         wait     = self . min_interval - elapsed         if wait > 0 :             time . sleep ( wait )         self . last_request = time . time ( )     def post ( self , endpoint: str , payload: dict ) - > dict :         self ._wait_if_needed ( )         headers = { "Authorization" : f "Bearer {self.api_key}" }         try :             resp = requests. post (                 self . base_url + endpoint ,                 headers = headers , json = payload , timeout = 30             )             # Handle 429 Too Many Requests: wait and retry once             if resp. status_code == 429 :                 retry_after = int ( resp. headers . get ( "Retry-After" , 5 ) )                 print ( f "触发限速,等待 {retry_after} 秒后重试..." )                 time . sleep ( retry_after )                 resp = requests. post (                     self . base_url + endpoint ,                     headers = headers , json = payload , timeout = 30                 )             resp. raise_for_status ( )             return resp. json ( )         except Exception as e:             return { "error" : str ( e ) } --- ## Response result cache 对于相同输入会返回相同结果的 API,可以将结果缓存到本地文件,避免重复请求,既省钱又提速。 ## 实例 # File path: scripts/cached_api.py import hashlib import json import os CACHE_DIR = "/home/claude/.api_cache" os . makedirs ( CACHE_DIR , exist_ok = True ) def _cache_key ( endpoint: str , payload: dict ) - > str :     """根据请求内容生成缓存键(MD5 哈希)"""     raw = json. dumps ( { "endpoint" : endpoint , "payload" : payload } ,                      sort_keys = True )     return hashlib. md5 ( raw. encode ( ) ) . hexdigest ( ) def cached_call ( endpoint: str , payload: dict , call_fn ) - > dict :     """     带缓存的 API 调用     参数:         endpoint: API 路径         payload:  请求体         call_fn:  实际发出 HTTP 请求的函数     返回:         API 响应(命中缓存时直接返回缓存结果)     """     key       = _cache_key ( endpoint , payload )     cache_file = os . path . join ( CACHE_DIR , f "{key}.json" )     # Cache hit     if os . path . exists ( cache_file ) :         with open ( cache_file , "r" ) as f:             print ( f "缓存命中:{key[:8]}..." )             return json. load ( f )     # Miss, send real request     result = call_fn ( endpoint , payload )     # Save to cache (only cache successful results)     if "error" not in result:         with open ( cache_file , "w" ) as f:             json. dump ( result , f , ensure_ascii = False )     return result