📚 2024级7班作业公布站 API 文档

为其他平台提供作业数据的 RESTful API 接口

📋 API 概览

基础信息

项目 说明
协议 HTTP / HTTPS
数据格式 JSON
字符编码 UTF-8
实时更新 WebSocket 支持

基础 URL

http://hm.zhufenggh.xyz/api

数据模型 - 作业 (Homework)

{
  // 作业唯一ID
  "id": "1775205413304",
  
  // 作业标题
  "title": "第三章课后习题",
  
  // 科目:语文、数学、英语、物理、化学、生物、历史、地理、政治、其他
  "subject": "语文",
  
  // 作业内容(支持 Markdown)
  "content": "完成课本第 25-30 页习题",
  
  // 相关链接数组
  "links": [
    {
      "title": "电子课本",
      "url": "https://example.com/book"
    }
  ],
  
  // 是否今晚收
  "tonight": false,
  
  // 创建时间(ISO 8601)
  "createdAt": "2026-04-03T08:36:53.304Z",
  
  // 更新时间(ISO 8601)
  "updatedAt": "2026-04-03T08:36:57.463Z"
}

数据模型 - 公告 (Notice)

{
  "content": "欢迎使用作业公布站!"
}

📝 作业接口

GET /api/homework 公开
获取所有作业列表,按发布时间倒序排列(最新的在前)

请求示例

# cURL
curl -X GET http://your-domain.com/api/homework

# JavaScript (Fetch)
fetch('http://hm.zhufenggh.xyz/api/homework')
  .then(res => res.json())
  .then(data => console.log(data));

# Python
import requests
response = requests.get('http://hm.zhufenggh.xyz/api/homework')
data = response.json()

响应示例

// 200 OK
[
  {
    "id": "1775205413304",
    "title": "第三章课后习题",
    "subject": "语文",
    "content": "完成课本第 25-30 页习题",
    "links": [],
    "tonight": false,
    "createdAt": "2026-04-03T08:36:53.304Z",
    "updatedAt": "2026-04-03T08:36:57.463Z"
  }
]
POST /api/homework 需管理权限
创建新作业,创建成功后会通过 WebSocket 广播到所有连接的客户端

请求参数

参数名 类型 必填 说明
title string 作业标题
subject string 科目名称
content string 作业内容(支持 Markdown)
links array 相关链接数组,格式:[{title, url}]
tonight boolean 是否今晚收,默认 false

请求示例

# cURL
curl -X POST http://your-domain.com/api/homework \
  -H "Content-Type: application/json" \
  -d '{
    "title": "第三章课后习题",
    "subject": "语文",
    "content": "完成课本第 25-30 页习题",
    "links": [{"title": "电子课本", "url": "https://example.com"}],
    "tonight": true
  }'

# JavaScript
fetch('http://hm.zhufenggh.xyz/api/homework', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: '第三章课后习题',
    subject: '语文',
    content: '完成课本第 25-30 页习题',
    tonight: true
  })
})

响应示例

// 200 OK
{
  "id": "1775205413304",
  "title": "第三章课后习题",
  "subject": "语文",
  "content": "完成课本第 25-30 页习题",
  "links": [],
  "tonight": true,
  "createdAt": "2026-04-03T08:36:53.304Z",
  "updatedAt": "2026-04-03T08:36:53.304Z"
}
PUT /api/homework/:id 需管理权限
更新指定ID的作业,更新成功后会通过 WebSocket 广播

路径参数

参数名 类型 说明
id string 作业ID

请求参数

与 POST /api/homework 相同

响应示例

// 200 OK
{
  "id": "1775205413304",
  "title": "更新后的标题",
  "subject": "语文",
  "content": "更新后的内容",
  "links": [],
  "tonight": false,
  "createdAt": "2026-04-03T08:36:53.304Z",
  "updatedAt": "2026-04-03T09:00:00.000Z"
}

// 404 Not Found
{
  "error": "作业不存在"
}
DELETE /api/homework/:id 需管理权限
删除指定ID的作业,删除成功后会通过 WebSocket 广播

响应示例

// 200 OK
{
  "success": true
}

// 404 Not Found
{
  "error": "作业不存在"
}

📢 公告接口

GET /api/notice 公开
获取当前公告内容

响应示例

// 200 OK
{
  "content": "欢迎使用作业公布站!"
}
PUT /api/notice 需管理权限
更新公告内容,更新成功后会通过 WebSocket 广播

请求参数

参数名 类型 必填 说明
content string 公告内容

响应示例

// 200 OK
{
  "content": "新的公告内容"
}

📊 统计接口

GET /api/stats 需管理权限
获取访问统计数据,包括总访问次数和最近的访问记录

响应示例

// 200 OK
{
  "totalVisits": 152,
  "visits": [
    {
      "id": "1775205413304",
      "timestamp": "2026-04-03T08:36:53.304Z",
      "userAgent": "Mozilla/5.0 ...",
      "ip": "192.168.1.1"
    }
  ]
}

💻 示例代码

JavaScript - 获取并显示作业

async function loadHomework() {
  try {
    const response = await fetch('http://your-domain.com/api/homework');
    const homework = await response.json();
    
    // 按科目过滤
    const mathHomework = homework.filter(h => h.subject === '数学');
    
    // 显示今晚收的作业
    const tonightHomework = homework.filter(h => h.tonight);
    
    console.log('作业列表:', homework);
  } catch (error) {
    console.error('加载失败:', error);
  }
}

loadHomework();

Python - 获取作业数据

import requests
import json

def get_homework():
    url = 'http://hm.zhufenggh.xyz/api/homework'
    response = requests.get(url)
    
    if response.status_code == 200:
        data = response.json()
        print(f"共获取到 {len(data)} 条作业")
        
        for item in data:
            print(f"[{item['subject']}] {item['title']}")
            if item['tonight']:
                print("  ⚠️ 今晚收!")
        
        return data
    else:
        print(f"请求失败: {response.status_code}")
        return None

homework = get_homework()

WebSocket 实时更新

// 连接 WebSocket 实时接收更新
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}`;
const ws = new WebSocket(wsUrl);

ws.onopen = () => {
  console.log('✅ 实时连接已建立');
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  
  switch (message.type) {
    case 'homework_created':
      console.log('📝 新作业:', message.data);
      break;
    case 'homework_updated':
      console.log('✏️ 作业更新:', message.data);
      break;
    case 'homework_deleted':
      console.log('🗑️ 作业删除:', message.data.id);
      break;
    case 'notice_updated':
      console.log('📢 公告更新:', message.data);
      break;
  }
};

ws.onclose = () => {
  console.log('❌ 连接断开,3秒后重连...');
  setTimeout(() => location.reload(), 3000);
};