YouTip LogoYouTip

Ai Api Development

AI API Development | Rookie Tutorial

\n\n

Using 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\n

API (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\n

Imagine 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
\n

The 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
\n\n

API Basic Concepts

\n\n

Before writing code, let's first understand a few core concepts.

\n\n

What is an API

\n\n

An 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\n

Using 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
\n\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\n

REST API Basic Principles

\n\n

REST (Representational State Transfer) is currently the most popular API design style.

\n\n

Simply put, it uses the HTTP protocol for communication:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
HTTP MethodPurposeExample in AI API
POSTCreate resourceSend chat request, generate image
GETGet resourceQuery model list, get billing information
DELETEDelete resourceDelete conversation history
\n\n

AI APIs are mostly POST requests, because we are "sending content to AI for processing."

\n\n

JSON Format Introduction

\n\n

JSON (JavaScript Object Notation) is the most commonly used data format in API communication.

\n\n

JSON syntax is very simpleβ€”it's a combination of key-value pairs.

\n\n

Example

\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\n

This is a typical AI API request body.

\n\n

A 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
\n\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\n

To do a good job, one must first sharpen one's tools.

\n\n

Python Installation and Configuration

\n\n

Python is the most commonly used language for calling AI APIs, with a complete ecosystem and rich libraries.

\n\n

First, 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\n

Python 3.9 or higher is recommended.

\n\n

If not installed yet, download the latest stable version from python.org.

\n\n

pip Package Management

\n\n

pip 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\n

Code Editor Selection

\n\n

For writing AI API code, one of the following editors is recommended:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
EditorFeaturesSuitable For
VS CodeFree, rich plugins, lightweightMost developers
CursorBuilt-in AI assistance, can directly generate codeThose who want AI to help write code
PyCharmMost comprehensive features, best Python supportProfessional Python developers
\n\n

The example code in this tutorial can run in any editor.

\n\n
\n\n

OpenAI API Introduction

\n\n

OpenAI API is the most classic and ecologically complete AI API, and many other vendors also support its format.

\n\n

Registration and Obtaining API Key

\n\n

An 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
\n

Important: Never commit your API Key to public code repositories. Once leaked, others may use your quota and incur charges.

\n
\n\n

First API Call

\n\n

First, install the official OpenAI SDK:

\n\n
pip install openai\n
\n\n

Now write the first API call program:

\n\n

Example

\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\n

If 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\n

Example

\n\n
from 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\n

Run this program:

\n\n
python first_api_call.py\n
\n\n

If everything is normal, you will see output similar to this:

\n\n
Full 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\n

Congratulations! You have successfully called an AI API.

\n\n

Request Parameters Explained

\n\n

OpenAI API has many parameters that can be adjusted. Here are the most commonly used ones:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Parameter NameTypeRequiredDescriptionDefault Value
modelstringYesModel ID to use, such as gpt-3.5-turbo, gpt-4None
messagesarrayYesConversation history message listNone
temperaturenumberNoSampling temperature, between 0-2, higher is more random, lower is more deterministic1.0
max_tokensintegerNoMaximum number of tokens to generateUnlimited
top_pnumberNoNucleus sampling parameter, between 0-11.0
stopstring/arrayNoStop sequence, stop generating when these characters are encounterednull
\n\n

Let's focus on temperature, which is the most commonly used adjustment parameter:

\n\n

Example

\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\n

A 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
\n\n

Anthropic Claude API

\n\n

Claude is Anthropic's large model, known for its safety and long-text processing capabilities.

\n\n

Differences and Similarities with OpenAI API

\n\n

Both can do text generation, but their design philosophies differ:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Comparison ItemOpenAI APIClaude API
Message structuresystem, user, assistant alternatesystem set separately, user, assistant alternate
Context length16k-128k variesClaude 3 series supports 200k
Parameter designtemperature, top_p, etc.temperature, top_p, etc., similar concepts
\n\n

Claude Messages API Structure

\n\n

First, install the Claude SDK:

\n\n
pip install anthropic\n
\n\n

Basic Claude API call:

\n\n

Example

\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\n

Similarly, we can replace with domestically compatible large models, such as DeepSeek, specifying the api_key, base_url, and model these three parameters:

\n\n

Example

\n\n
import 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\n

System Prompt Setting

\n\n

In Claude API, System Prompt is an independent parameter, not placed in the messages array:

\n\n

Example

\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\n

Single-turn conversation is simple, but truly useful applications all need to "remember context."

\n\n

Conversation History Maintenance Method

\n\n

The idea is simple: store all previous conversations and send them to the AI together with each request.

\n\n

Example

\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
← Ai MultimodalAi Industry β†’