API documentation is like a user manual that tells other developers how to use your provided services.
Simple Analogies:
If an API is a coffee machine, then API documentation is its instruction manual
If an API is a LEGO set, then API documentation is its assembly guide
Why Do We Need API Documentation?
Good API documentation provides several benefits:
Reduces Learning Curve: New users can quickly get started
Minimizes Communication Overhead: Reduces repetitive questions
Improves Development Efficiency: Clear instructions prevent misuse
Reduces Maintenance Burden: Users can solve problems independently
Characteristics of Good API Documentation
👍 Clear and Understandable: As natural as talking to a friend
👍 Well-Structured: As organized as a library shelf
👍 Rich in Examples: As detailed as a cooking recipe
👍 Regularly Updated: As current as news updates
Preparation Before Writing API Documentation
1. Understanding Your Audience
Different readers need different information:
Reader Type |
Focus Areas |
Examples |
Junior Developers |
Basic concepts and detailed steps |
How to obtain API keys, how to make first request |
Senior Developers |
Technical details and advanced features |
Performance optimization, error handling |
Project Managers |
Feature overview and business value |
Problem-solving capabilities, integration methods |
2. Essential Documentation Checklist
Required basic information:
📝 API Basic Information
API server address
Supported protocols (e.g., HTTP/HTTPS)
API version information
🔐 Authentication Information
Authentication methods (e.g., API key, OAuth2.0)
Acquisition and configuration methods
📚 Endpoint Information
List of available APIs
Detailed description of each endpoint
Request and response examples
3. Choosing Appropriate Documentation Tools
Recommended tools:
Swagger/OpenAPI: Generates interactive documentation
GitBook: Suitable for detailed documentation
Markdown: Lightweight markup language for basic documentation
Apidog: API testing and documentation generation, supports IntelliJ IDEA plugin for one-click API doc generation.
You can use any of the tools mentioned above to assist in writing API documentation. My preferred tool is Apidog, which supports Markdown writing. .md
files can coexist with API endpoints, and they can be quickly imported via IntelliJ IDEA plugin or Swagger/OpenAPI documentation. API documentation can be shared, and if the shared documentation includes endpoints, they can be tested online, making the process quite convenient.
API Documentation Structure Example
Note: The following screenshots are examples of public online documentation from Apidog and are provided for reference only.
1. Documentation Overview
An overview is the "first impression" of your API documentation, serving as the cover and table of contents:
# Weather Query API Documentation
Version: v1.0
Last Updated: 2024-01-20
## Introduction
This API provides weather query services for major global cities, supporting real-time weather and 7-day forecasts.
## Basic Information
- Service URL: https://api.weather.example.com
- Protocol: HTTPS
- Data Format: JSON
- Encoding: UTF-8
For example:
2. Authentication Section
Authentication is like the "access control system" of your API. This section is essential because it helps users understand access rights, ensures API security, and prevents unauthorized usage.
For example:
## Authentication Method
All API requests require an API key in the header:
Header Format:
X-API-Key: your_api_key_here
Steps to Obtain API Key:
1. Register account: https://weather.example.com/register
2. Access console: https://weather.example.com/console
3. Generate API key
3. Endpoint Description Example
Endpoint documentation is the core content of API documentation. It specifies:
How to construct requests
Required parameters
Parameter specifications
For example:
## Get Real-time Weather
Retrieve real-time weather information for a specified city.
### Request Information
- Method: GET
- Path: /v1/weather/current
- Complete URL: https://api.weather.example.com/v1/weather/current
### Request Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| city | string | Yes | City name, e.g., "Tokyo" |
| lang | string | No | Response language, default "en_US" |
### Request Example
```
curl
curl -X GET "https://api.weather.example.com/v1/weather/current?city=Tokyo" \
-H "X-API-Key: your_api_key_here"
4. Response Example
Response examples serve as "expected output demonstrations." Their importance lies in:
Showing users what data they'll receive
Helping users plan data processing logic
Reducing trial and error
For example:
JSON
{
"code": 200,
"data": {
"city": "Tokyo",
"temperature": 20,
"humidity": 65,
"weather": "Sunny",
"updated_at": "2024-01-20T10:00:00Z"
}
}
5. Error Code Documentation
Helps users quickly identify issues and provides clear solutions.For example:
Error Code |
Description |
Solution |
400 |
Invalid Request Parameters |
Verify parameter correctness |
401 |
Unauthorized |
Check API key validity |
404 |
City Not Found |
Verify city name |
See how leading projects use Apidog to create polished API documentation:
Medusa Docs:medusa.apidog.io
Salla Docs:docs.salla.dev
Subscan Docs:support.subscan.io
Ready to elevate your documentation? Try Apidog today!
Practical Code Examples
It is necessary to include example code in common programming languages in the API documentation to help users understand how to call the API.For example:
1. Python Example
Python
import requests
def get_weather(city):
api_key = 'your_api_key_here'
url = 'https://api.weather.example.com/v1/weather/current'
headers = {
'X-API-Key': api_key
}
params = {
'city': city
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
data = response.json()
return data['data']
else:
return f"Error: {response.status_code}"
# Usage Example
weather = get_weather('Tokyo')
print(f"Current temperature: {weather['temperature']}°C")
2. JavaScript Example
JavaScript
async function getWeather(city) {
const API_KEY = 'your_api_key_here';
const url = `https://api.weather.example.com/v1/weather/current?city=${city}`;
try {
const response = await fetch(url, {
headers: {
'X-API-Key': API_KEY
}
});
const data = await response.json();
return data.data;
} catch (error) {
console.error('Failed to fetch weather data:', error);
}
}
// Usage Example
getWeather('Tokyo')
.then(weather => console.log(`Current temperature: ${weather.temperature}°C`));
Frequently Asked Questions (FAQ)
Adding a FAQ section to the API documentation can greatly reduce technical support costs.For example:
JSON
## 1. API Call Issues
Q: Why am I getting a 401 error on my API request?
A: Common reasons include:
- API key not properly set in request header
- Expired API key
- Invalid API key
## 2. Data Issues
Q: Why can't I find weather data for certain cities?
A: Possible reasons:
- Incorrect city name spelling
- City not in supported list
- Temporary server inability to fetch city data
Best Practices
1. Documentation Writing Guidelines
✅ Do's:
Use clear, simple language
Provide comprehensive code examples
Update documentation regularly
Maintain consistent formatting
❌ Don'ts:
Use obscure technical jargon
Omit error handling documentation
Ignore example code
Change document structure arbitrarily
2. API Usage Guidelines
Handle all possible error scenarios
Control request frequency appropriately
Regularly verify API key validity
Maintain proper logging
Additional Resources
1. Recommended Tools
Name |
Purpose |
Features |
Swagger |
API Documentation Generation |
Automated, Interactive |
GitBook |
Documentation Hosting |
Version Control, Collaboration |
API Testing & Documentation |
Version Control, Easy Debugging, IntelliJ IDEA plugin Support |
2. Learning Resources
Swagger Documentation: https://swagger.io/docs/
Apidog Documentation: https://docs.Apidog.com/
Summary
1. Key Documentation Points
User-centric approach
Maintain simplicity
Provide concrete examples
Continuous maintenance and updates
2. Checklist
Complete basic information
Clear authentication methods
Comprehensive code examples
Complete error handling
Consistent formatting
This comprehensive guide to API documentation writing emphasizes that good documentation is an ongoing process of improvement based on user feedback.
Top comments (0)