AI API Development | Rookie Tutorial
\n\nUsing AI chat tools in a web interface is convenient, but to truly integrate AI capabilities into your own products, workflows, and automation scripts, what you need is an API.
\n\nAPI (Application Programming Interface) is the bridge for communication between applications. Through an API, your code can directly send requests to AI models and receive responses, without manually opening a webpage to copy and paste.
\n\nImagine these scenarios:
\n\n- \n
- Your e-commerce website automatically generates description copy for each product. \n
- Your note-taking app automatically summarizes long texts input by users. \n
- Your customer service system automatically categorizes and responds to user inquiries. \n
- These features can all be implemented through AI APIs. \n
\n\n\nThe goal of this module is to transform you from "only knowing how to chat with AI" to "making AI work in your code."
\n
\n\n
API Basic Concepts
\n\nBefore writing code, let's first understand a few core concepts.
\n\nWhat is an API
\n\nAn API is a set of agreed-upon communication methods. We send requests in a specific format, and the other party returns results in a specific format.
\n\nUsing ordering food as an analogy:
\n\n- \n
- You walk into a restaurant, get the menu (API documentation), and know what you can order and how to order it (request format). \n
- You tell the waiter: one Kung Pao Chicken, less spicy (sending an API request). \n
- The kitchen prepares the dish and brings it to you (returning an API response). \n
In this process, you don't need to enter the kitchen or know how the dish is cookedβthis is the value of an API: encapsulating complex details and exposing only a simple interface.
\n\nREST API Basic Principles
\n\nREST (Representational State Transfer) is currently the most popular API design style.
\n\nSimply put, it uses the HTTP protocol for communication:
\n\n| HTTP Method | \nPurpose | \nExample in AI API | \n
|---|---|---|
| POST | \nCreate resource | \nSend chat request, generate image | \n
| GET | \nGet resource | \nQuery model list, get billing information | \n
| DELETE | \nDelete resource | \nDelete conversation history | \n
AI APIs are mostly POST requests, because we are "sending content to AI for processing."
\n\nJSON Format Introduction
\n\nJSON (JavaScript Object Notation) is the most commonly used data format in API communication.
\n\nJSON syntax is very simpleβit's a combination of key-value pairs.
\n\nExample
\n\n{\n "model":"gpt-4",\n "messages":[\n {\n "role":"user",\n "content":"Hello, please introduce TUTORIAL"\n }\n ],\n "temperature":0.7,\n "max_tokens":1000\n}\n\n\nThis is a typical AI API request body.
\n\nA few core rules:
\n\n- \n
- Objects are wrapped with
{ }, arrays are wrapped with.\n - Strings use double quotes
", not single quotes. \n - Key-value pairs are separated by colons
:, and keys must be strings. \n - Multiple key-value pairs are separated by commas
,. \n
JSON looks very similar to Python dictionaries, but there are syntactic differencesβpay attention when writing code.
\n\n\n\n
Development Environment Setup
\n\nTo do a good job, one must first sharpen one's tools.
\n\nPython Installation and Configuration
\n\nPython is the most commonly used language for calling AI APIs, with a complete ecosystem and rich libraries.
\n\nFirst, check if Python is installed on your computer:
\n\n# Check Python version (universal for Windows, macOS, Linux)\npython --version\n# or\npython3 --version\n\n\nPython 3.9 or higher is recommended.
\n\nIf not installed yet, download the latest stable version from python.org.
\n\npip Package Management
\n\npip is Python's package manager, used to install third-party libraries.
\n\n# Check pip version\npip --version\n# or\npip3 --version\n\n# Upgrade pip to the latest version\npip install --upgrade pip\n\n# Configure domestic mirror source (optional, improves download speed)\npip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n\n\nCode Editor Selection
\n\nFor writing AI API code, one of the following editors is recommended:
\n\n| Editor | \nFeatures | \nSuitable For | \n
|---|---|---|
| VS Code | \nFree, rich plugins, lightweight | \nMost developers | \n
| Cursor | \nBuilt-in AI assistance, can directly generate code | \nThose who want AI to help write code | \n
| PyCharm | \nMost comprehensive features, best Python support | \nProfessional Python developers | \n
The example code in this tutorial can run in any editor.
\n\n\n\n
OpenAI API Introduction
\n\nOpenAI API is the most classic and ecologically complete AI API, and many other vendors also support its format.
\n\nRegistration and Obtaining API Key
\n\nAn API Key is your passβit proves your identity and records your usage. Steps to obtain:
\n\n- \n
- 1. Visit platform.openai.com to register an account \n
- 2. Go to the API Keys page \n
- 3. Click "Create new secret key" \n
- 4. Copy and save this Key (shown only once!) \n
\n\n\nImportant: Never commit your API Key to public code repositories. Once leaked, others may use your quota and incur charges.
\n
First API Call
\n\nFirst, install the official OpenAI SDK:
\n\npip install openai\n\n\nNow write the first API call program:
\n\nExample
\n\n# File path: first_api_call.py\n# First OpenAI API call example\n\nfrom openai import OpenAI\n\n# Initialize client\n# Note: API Key is recommended to be read from environment variables, do not hardcode in code\n# Here it's written directly for demonstration convenience; use environment variables in actual projects\n\nclient = OpenAI(\n api_key="your-api-key-here" # Replace with your API Key\n)\n\n# Send chat request\nresponse = client.chat.completions.create(\n model="gpt-3.5-turbo", # Select model\n messages=[\n {\n "role": "user", # Role: user indicates the user\n "content": "Please introduce TUTORIAL in one sentence " # User input content\n }\n ]\n)\n\n# Print full response (see what was returned)\nprint("Full Response:")\nprint(response)\nprint("n" + "="*50 + "n")\n\n# Extract AI's reply\nai_reply = response.choices.message.content\nprint("AI Reply:")\nprint(ai_reply)\n\n\nIf you don't have an OpenAI api_key, you can also use domestic alternatives. Many domestic models are compatible with OpenAI, such as DeepSeek. You can apply for an api_key at https://platform.deepseek.com/api_keys, then replace your api_key and model in the following code. DeepSeek supports models like deepseek-v4-flash and deepseek-v4-pro (thinking mode), and you can use API calls to large models:
\n\nExample
\n\nfrom openai import OpenAI\n\n# Initialize client\n# Note: API Key is recommended to be read from environment variables, do not hardcode in code\n# Here it's written directly for demonstration convenience; use environment variables in actual projects\n\nclient = OpenAI(\n api_key="sk-xxxx", # Set api_key\n base_url="https://api.deepseek.com") # Set request URL\n\n# Send chat request\nresponse = client.chat.completions.create(\n model="deepseek-v4-flash", # Select model\n messages=[\n {\n "role": "user", # Role: user indicates the user\n "content": "Please introduce TUTORIAL in one sentence " # User input content\n }\n ]\n)\n\n# Print full response (see what was returned)\nprint("Full Response:")\nprint(response)\nprint("n" + "="*50 + "n")\n\n# Extract AI's reply\nai_reply = response.choices.message.content\nprint("AI Reply:")\nprint(ai_reply)\n\n\nRun this program:
\n\npython first_api_call.py\n\n\nIf everything is normal, you will see output similar to this:
\n\nFull Response:ChatCompletion(id='chatcmpl-xxx', choices=[Choice(finish_reason='stop', index=0, message=ChatMessage(content='TUTORIAL is a learning platform focused on providing programming technology tutorials...', role='assistant'))], model='gpt-3.5-turbo', usage=CompletionUsage(completion_tokens=30, prompt_tokens=18, total_tokens=48))================================================== AI Reply: TUTORIAL is a learning platform focused on providing programming technology tutorialsοΌCovers multiple programming languages and technical fields.\n\n\nCongratulations! You have successfully called an AI API.
\n\nRequest Parameters Explained
\n\nOpenAI API has many parameters that can be adjusted. Here are the most commonly used ones:
\n\n| Parameter Name | \nType | \nRequired | \nDescription | \nDefault Value | \n
|---|---|---|---|---|
| model | \nstring | \nYes | \nModel ID to use, such as gpt-3.5-turbo, gpt-4 | \nNone | \n
| messages | \narray | \nYes | \nConversation history message list | \nNone | \n
| temperature | \nnumber | \nNo | \nSampling temperature, between 0-2, higher is more random, lower is more deterministic | \n1.0 | \n
| max_tokens | \ninteger | \nNo | \nMaximum number of tokens to generate | \nUnlimited | \n
| top_p | \nnumber | \nNo | \nNucleus sampling parameter, between 0-1 | \n1.0 | \n
| stop | \nstring/array | \nNo | \nStop sequence, stop generating when these characters are encountered | \nnull | \n
Let's focus on temperature, which is the most commonly used adjustment parameter:
\n\nExample
\n\n# File path: temperature_demo.py\n# Demonstrate the effect of temperature parameter on output\n\nfrom openai import OpenAI\n\nclient = OpenAI(api_key="your-api-key-here")\n\ndef ask_ai(temperature_value: float, question: str) -> str:\n """Ask with specified temperature"""\n response = client.chat.completions.create(\n model="gpt-3.5-turbo",\n messages=[{"role": "user", "content": question}],\n temperature=temperature_value,\n max_tokens=200\n )\n return response.choices.message.content\n\n# Same question, asked three times with different temperatures\nquestion = "Give TUTORIAL Create a slogan"\n\nprint("--- temperature=0οΌMost deterministic, results are similar each time)---")\nprint(ask_ai(0.0, question))\n\nprint("n--- temperature=0.7οΌBalanced, recommended for daily use)---")\nprint(ask_ai(0.7, question))\n\nprint("n--- temperature=1.8οΌMost random, results vary greatly each time)---")\nprint(ask_ai(1.8, question))\n\n\nA rule of thumb:
\n\n- \n
- temperature=0: Factual answers, code generation, scenarios requiring precise results \n
- temperature=0.7: Daily conversations, general tasks \n
- temperature>1.0: Creative writing, brainstorming \n
\n\n
Anthropic Claude API
\n\nClaude is Anthropic's large model, known for its safety and long-text processing capabilities.
\n\nDifferences and Similarities with OpenAI API
\n\nBoth can do text generation, but their design philosophies differ:
\n\n| Comparison Item | \nOpenAI API | \nClaude API | \n
|---|---|---|
| Message structure | \nsystem, user, assistant alternate | \nsystem set separately, user, assistant alternate | \n
| Context length | \n16k-128k varies | \nClaude 3 series supports 200k | \n
| Parameter design | \ntemperature, top_p, etc. | \ntemperature, top_p, etc., similar concepts | \n
Claude Messages API Structure
\n\nFirst, install the Claude SDK:
\n\npip install anthropic\n\n\nBasic Claude API call:
\n\nExample
\n\n# File path: claude_first_call.py\n# Claude API basic call example\n\nimport anthropic\n\n# Initialize client\nclient = anthropic.Anthropic(\n api_key="your-api-key-here" # Replace with your Claude API Key\n)\n\n# Send message request\nresponse = client.messages.create(\n model="claude-3-sonnet-20240229", # Select Claude model\n max_tokens=1024, # Claude requires max_tokens to be set\n messages=[\n {\n "role": "user",\n "content": "Please introduce TUTORIAL in three sentences"\n }\n ]\n)\n\n# Print response\nprint("Full Response:")\nprint(response)\nprint("n" + "="*50 + "n")\n\n# Extract reply\nprint("Claude Reply:")\nprint(response.content.text)\n\n\nSimilarly, we can replace with domestically compatible large models, such as DeepSeek, specifying the api_key, base_url, and model these three parameters:
\n\nExample
\n\nimport anthropic\n\n# Initialize client\nclient = anthropic.Anthropic(\n api_key="sk-xxx", # Replace with your API Key\n base_url="https://api.deepseek.com/anthropic" # Claude API base URL\n)\n\n# Send message request\nresponse = client.messages.create(\n model="deepseek-v4-flash", # Select Claude model\n max_tokens=1024, # Claude requires max_tokens to be set\n messages=[\n {\n "role": "user",\n "content": "Please introduce TUTORIAL in three sentences"\n }\n ]\n)\n\n# Print response\nprint("Full Response:")\nprint(response)\nprint("n" + "="*50 + "n")\n\n# Extract reply\nprint("Claude Reply:")\nprint(response.content.thinking)\n\n\nSystem Prompt Setting
\n\nIn Claude API, System Prompt is an independent parameter, not placed in the messages array:
\n\nExample
\n\n# File path: claude_system_prompt.py\n# Claude System Prompt usage example\n\nimport anthropic\n\nclient = anthropic.Anthropic(api_key="your-api-key-here")\n\nresponse = client.messages.create(\n model="claude-3-sonnet-20240229",\n max_tokens=1024,\n # System Prompt is set here\n system="You are a professional technical documentation editor, answers should be concise and accurate, use list format frequently.",\n messages=[\n {\n "role": "user",\n "content": "What core knowledge points should be mastered when learning Python?"\n }\n ]\n)\n\nprint(response.content.text)\n\n\n\n\n
Multi-turn Conversation Management
\n\nSingle-turn conversation is simple, but truly useful applications all need to "remember context."
\n\nConversation History Maintenance Method
\n\nThe idea is simple: store all previous conversations and send them to the AI together with each request.
\n\nExample
\n\n# File path: multi_turn_chat.py\n# Multi-turn conversation management example\n\nfrom openai import OpenAI\n\nclient = OpenAI(api_key="your-api-key-here")\n\nclass ChatBot:\n """A simple multi-turn conversation bot"""\n \n def __init__(self, system_prompt: str="You are a helpful
YouTip