[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FP319A3AGTCPPC1H3AJ72E":3,"skill-same:01M6FP319A3AGTCPPC1H3AJ72E":91},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":30,"publishedAt":51,"linkOnly":52,"markdownContent":53,"markdownBody":54,"frontMatter":55,"refName":64,"commitSha":65,"skillDirectory":66,"forksCount":67,"repositoryHtmlUrl":68,"repositoryHomepageUrl":6,"ownerHtmlUrl":69,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":70,"install":71,"resources":84},"01M6FP319A3AGTCPPC1H3AJ72E","api-dev",null,"Scaffold, test, document, and debug REST and GraphQL APIs. Use when the user needs to create API endpoints, write integration tests, generate OpenAPI specs, test with curl, mock APIs, or troubleshoot HTTP issues.","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fgitgoodordietrying\u002Fapi-dev\u002FSKILL.md",[17,22,25],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50],"api dev","dev","api","openapi","mock","tests","document","use","write","node","python3","linux","issues","win32","generate","create","http","debug","integration tests","troubleshoot","2026-11-10 10:12:30",false,"---\nname: api-dev\ndescription: Scaffold, test, document, and debug REST and GraphQL APIs. Use when the user needs to create API endpoints, write integration tests, generate OpenAPI specs, test with curl, mock APIs, or troubleshoot HTTP issues.\nmetadata: {\"clawdbot\":{\"emoji\":\"?\",\"requires\":{\"anyBins\":[\"curl\",\"node\",\"python3\"]},\"os\":[\"linux\",\"darwin\",\"win32\"]}}\n---\n\n# API Development\n\nBuild, test, document, and debug HTTP APIs from the command line. Covers the full API lifecycle: scaffolding endpoints, testing with curl, generating OpenAPI docs, mocking services, and debugging.\n\n## When to Use\n\n- Scaffolding new REST or GraphQL endpoints\n- Testing APIs with curl or scripts\n- Generating or validating OpenAPI\u002FSwagger specs\n- Mocking external APIs for development\n- Debugging HTTP request\u002Fresponse issues\n- Load testing endpoints\n\n## Testing APIs with curl\n\n### GET requests\n\n```bash\n# Basic GET\ncurl -s https:\u002F\u002Fapi.example.com\u002Fusers | jq .\n\n# With headers\ncurl -s -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Accept: application\u002Fjson\" \\\n  https:\u002F\u002Fapi.example.com\u002Fusers | jq .\n\n# With query params\ncurl -s \"https:\u002F\u002Fapi.example.com\u002Fusers?page=2&limit=10\" | jq .\n\n# Show response headers too\ncurl -si https:\u002F\u002Fapi.example.com\u002Fusers\n```\n\n### POST\u002FPUT\u002FPATCH\u002FDELETE\n\n```bash\n# POST JSON\ncurl -s -X POST https:\u002F\u002Fapi.example.com\u002Fusers \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -d '{\"name\": \"Alice\", \"email\": \"alice@example.com\"}' | jq .\n\n# PUT (full replace)\ncurl -s -X PUT https:\u002F\u002Fapi.example.com\u002Fusers\u002F123 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"name\": \"Alice Updated\", \"email\": \"alice@example.com\"}' | jq .\n\n# PATCH (partial update)\ncurl -s -X PATCH https:\u002F\u002Fapi.example.com\u002Fusers\u002F123 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"name\": \"Alice V2\"}' | jq .\n\n# DELETE\ncurl -s -X DELETE https:\u002F\u002Fapi.example.com\u002Fusers\u002F123\n\n# POST form data\ncurl -s -X POST https:\u002F\u002Fapi.example.com\u002Fupload \\\n  -F \"file=@document.pdf\" \\\n  -F \"description=My document\"\n```\n\n### Debug requests\n\n```bash\n# Verbose output (see full request\u002Fresponse)\ncurl -v https:\u002F\u002Fapi.example.com\u002Fhealth 2>&1\n\n# Show only response headers\ncurl -sI https:\u002F\u002Fapi.example.com\u002Fhealth\n\n# Show timing breakdown\ncurl -s -o \u002Fdev\u002Fnull -w \"DNS: %{time_namelookup}s\\nConnect: %{time_connect}s\\nTLS: %{time_appconnect}s\\nFirst byte: %{time_starttransfer}s\\nTotal: %{time_total}s\\n\" https:\u002F\u002Fapi.example.com\u002Fhealth\n\n# Follow redirects\ncurl -sL https:\u002F\u002Fapi.example.com\u002Fold-endpoint\n\n# Save response to file\ncurl -s -o response.json https:\u002F\u002Fapi.example.com\u002Fdata\n```\n\n## API Test Scripts\n\n### Bash test runner\n\n```bash\n#!\u002Fbin\u002Fbash\n# api-test.sh - Simple API test runner\nBASE_URL=\"${1:-http:\u002F\u002Flocalhost:3000}\"\nPASS=0\nFAIL=0\n\nassert_status() {\n  local method=\"$1\" url=\"$2\" expected=\"$3\" body=\"$4\"\n  local args=(-s -o \u002Fdev\u002Fnull -w \"%{http_code}\" -X \"$method\")\n  if [ -n \"$body\" ]; then\n    args+=(-H \"Content-Type: application\u002Fjson\" -d \"$body\")\n  fi\n  local status\n  status=$(curl \"${args[@]}\" \"$BASE_URL$url\")\n  if [ \"$status\" = \"$expected\" ]; then\n    echo \"PASS: $method $url -> $status\"\n    ((PASS++))\n  else\n    echo \"FAIL: $method $url -> $status (expected $expected)\"\n    ((FAIL++))\n  fi\n}\n\nassert_json() {\n  local url=\"$1\" jq_expr=\"$2\" expected=\"$3\"\n  local actual\n  actual=$(curl -s \"$BASE_URL$url\" | jq -r \"$jq_expr\")\n  if [ \"$actual\" = \"$expected\" ]; then\n    echo \"PASS: GET $url | jq '$jq_expr' = $expected\"\n    ((PASS++))\n  else\n    echo \"FAIL: GET $url | jq '$jq_expr' = $actual (expected $expected)\"\n    ((FAIL++))\n  fi\n}\n\n# Health check\nassert_status GET \u002Fhealth 200\n\n# CRUD tests\nassert_status POST \u002Fapi\u002Fusers 201 '{\"name\":\"Test\",\"email\":\"test@test.com\"}'\nassert_status GET \u002Fapi\u002Fusers 200\nassert_json \u002Fapi\u002Fusers '.[-1].name' 'Test'\nassert_status DELETE \u002Fapi\u002Fusers\u002F1 204\n\n# Auth tests\nassert_status GET \u002Fapi\u002Fadmin 401\nassert_status GET \u002Fapi\u002Fadmin 403  # with wrong role\n\necho \"\"\necho \"Results: $PASS passed, $FAIL failed\"\n[ \"$FAIL\" -eq 0 ] && exit 0 || exit 1\n```\n\n### Python test runner\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"api_test.py - API integration test suite.\"\"\"\nimport json, sys, urllib.request, urllib.error\n\nBASE = sys.argv[1] if len(sys.argv) > 1 else \"http:\u002F\u002Flocalhost:3000\"\nPASS = FAIL = 0\n\ndef request(method, path, body=None, headers=None):\n    \"\"\"Make an HTTP request, return (status, body_dict, headers).\"\"\"\n    url = f\"{BASE}{path}\"\n    data = json.dumps(body).encode() if body else None\n    hdrs = {\"Content-Type\": \"application\u002Fjson\", \"Accept\": \"application\u002Fjson\"}\n    if headers:\n        hdrs.update(headers)\n    req = urllib.request.Request(url, data=data, headers=hdrs, method=method)\n    try:\n        resp = urllib.request.urlopen(req)\n        body = json.loads(resp.read().decode()) if resp.read() else None\n    except urllib.error.HTTPError as e:\n        return e.code, None, dict(e.headers)\n    return resp.status, body, dict(resp.headers)\n\ndef test(name, fn):\n    \"\"\"Run a test function, track pass\u002Ffail.\"\"\"\n    global PASS, FAIL\n    try:\n        fn()\n        print(f\"  PASS: {name}\")\n        PASS += 1\n    except AssertionError as e:\n        print(f\"  FAIL: {name} - {e}\")\n        FAIL += 1\n\ndef assert_eq(actual, expected, msg=\"\"):\n    assert actual == expected, f\"got {actual}, expected {expected}. {msg}\"\n\n# --- Tests ---\nprint(f\"Testing {BASE}\\n\")\n\ntest(\"GET \u002Fhealth returns 200\", lambda: (\n    assert_eq(request(\"GET\", \"\u002Fhealth\")[0], 200)\n))\n\ntest(\"POST \u002Fapi\u002Fusers creates user\", lambda: (\n    assert_eq(request(\"POST\", \"\u002Fapi\u002Fusers\", {\"name\": \"Test\", \"email\": \"t@t.com\"})[0], 201)\n))\n\ntest(\"GET \u002Fapi\u002Fusers returns array\", lambda: (\n    assert_eq(type(request(\"GET\", \"\u002Fapi\u002Fusers\")[1]), list)\n))\n\ntest(\"GET \u002Fapi\u002Fnotfound returns 404\", lambda: (\n    assert_eq(request(\"GET\", \"\u002Fapi\u002Fnotfound\")[0], 404)\n))\n\nprint(f\"\\nResults: {PASS} passed, {FAIL} failed\")\nsys.exit(0 if FAIL == 0 else 1)\n```\n\n## OpenAPI Spec Generation\n\n### Generate from existing endpoints\n\n```bash\n# Scaffold an OpenAPI 3.0 spec from curl responses\n# Run this, then fill in the details\ncat > openapi.yaml \u003C\u003C 'EOF'\nopenapi: \"3.0.3\"\ninfo:\n  title: My API\n  version: \"1.0.0\"\n  description: API description here\nservers:\n  - url: http:\u002F\u002Flocalhost:3000\n    description: Local development\npaths:\n  \u002Fhealth:\n    get:\n      summary: Health check\n      responses:\n        \"200\":\n          description: Service is healthy\n          content:\n            application\u002Fjson:\n              schema:\n                type: object\n                properties:\n                  status:\n                    type: string\n                    example: ok\n  \u002Fapi\u002Fusers:\n    get:\n      summary: List users\n      parameters:\n        - name: page\n          in: query\n          schema:\n            type: integer\n            default: 1\n        - name: limit\n          in: query\n          schema:\n            type: integer\n            default: 20\n      responses:\n        \"200\":\n          description: List of users\n          content:\n            application\u002Fjson:\n              schema:\n                type: array\n                items:\n                  $ref: \"#\u002Fcomponents\u002Fschemas\u002FUser\"\n    post:\n      summary: Create user\n      requestBody:\n        required: true\n        content:\n          application\u002Fjson:\n            schema:\n              $ref: \"#\u002Fcomponents\u002Fschemas\u002FCreateUser\"\n      responses:\n        \"201\":\n          description: User created\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: \"#\u002Fcomponents\u002Fschemas\u002FUser\"\n        \"400\":\n          description: Validation error\n  \u002Fapi\u002Fusers\u002F{id}:\n    get:\n      summary: Get user by ID\n      parameters:\n        - name: id\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        \"200\":\n          description: User details\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: \"#\u002Fcomponents\u002Fschemas\u002FUser\"\n        \"404\":\n          description: Not found\ncomponents:\n  schemas:\n    User:\n      type: object\n      properties:\n        id:\n          type: string\n        name:\n          type: string\n        email:\n          type: string\n          format: email\n        createdAt:\n          type: string\n          format: date-time\n    CreateUser:\n      type: object\n      required:\n        - name\n        - email\n      properties:\n        name:\n          type: string\n        email:\n          type: string\n          format: email\n  securitySchemes:\n    bearerAuth:\n      type: http\n      scheme: bearer\n      bearerFormat: JWT\nEOF\n```\n\n### Validate OpenAPI spec\n\n```bash\n# Using npx (no install needed)\nnpx @redocly\u002Fcli lint openapi.yaml\n\n# Quick check: is the YAML valid?\npython3 -c \"import yaml; yaml.safe_load(open('openapi.yaml'))\" && echo \"Valid YAML\"\n```\n\n## Mock Server\n\n### Quick mock with Python\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"mock_server.py - Lightweight API mock from OpenAPI-like config.\"\"\"\nimport json, http.server, re, sys\n\nPORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080\n\n# Define mock routes: (method, path_pattern) -> response\nROUTES = {\n    (\"GET\", \"\u002Fhealth\"): {\"status\": 200, \"body\": {\"status\": \"ok\"}},\n    (\"GET\", \"\u002Fapi\u002Fusers\"): {\"status\": 200, \"body\": [\n        {\"id\": \"1\", \"name\": \"Alice\", \"email\": \"alice@example.com\"},\n        {\"id\": \"2\", \"name\": \"Bob\", \"email\": \"bob@example.com\"},\n    ]},\n    (\"POST\", \"\u002Fapi\u002Fusers\"): {\"status\": 201, \"body\": {\"id\": \"3\", \"name\": \"Created\"}},\n    (\"GET\", r\"\u002Fapi\u002Fusers\u002F\\w+\"): {\"status\": 200, \"body\": {\"id\": \"1\", \"name\": \"Alice\"}},\n    (\"DELETE\", r\"\u002Fapi\u002Fusers\u002F\\w+\"): {\"status\": 204, \"body\": None},\n}\n\nclass MockHandler(http.server.BaseHTTPRequestHandler):\n    def _handle(self):\n        for (method, pattern), response in ROUTES.items():\n            if self.command == method and re.fullmatch(pattern, self.path.split('?')[0]):\n                self.send_response(response[\"status\"])\n                if response[\"body\"] is not None:\n                    self.send_header(\"Content-Type\", \"application\u002Fjson\")\n                    self.end_headers()\n                    self.wfile.write(json.dumps(response[\"body\"]).encode())\n                else:\n                    self.end_headers()\n                return\n        self.send_response(404)\n        self.send_header(\"Content-Type\", \"application\u002Fjson\")\n        self.end_headers()\n        self.wfile.write(json.dumps({\"error\": \"Not found\"}).encode())\n\n    do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _handle\n\n    def log_message(self, fmt, *args):\n        print(f\"{self.command} {self.path} -> {args[1] if len(args) > 1 else '?'}\")\n\nprint(f\"Mock server on http:\u002F\u002Flocalhost:{PORT}\")\nhttp.server.HTTPServer((\"\", PORT), MockHandler).serve_forever()\n```\n\nRun: `python3 mock_server.py 8080`\n\n## Node.js Express Scaffolding\n\n### Minimal REST API\n\n```javascript\n\u002F\u002F server.js - Minimal Express REST API\nconst express = require('express');\nconst app = express();\napp.use(express.json());\n\n\u002F\u002F In-memory store\nconst items = new Map();\nlet nextId = 1;\n\n\u002F\u002F CRUD endpoints\napp.get('\u002Fapi\u002Fitems', (req, res) => {\n  const { page = 1, limit = 20 } = req.query;\n  const all = [...items.values()];\n  const start = (page - 1) * limit;\n  res.json({ items: all.slice(start, start + +limit), total: all.length });\n});\n\napp.get('\u002Fapi\u002Fitems\u002F:id', (req, res) => {\n  const item = items.get(req.params.id);\n  if (!item) return res.status(404).json({ error: 'Not found' });\n  res.json(item);\n});\n\napp.post('\u002Fapi\u002Fitems', (req, res) => {\n  const { name, description } = req.body;\n  if (!name) return res.status(400).json({ error: 'name required' });\n  const id = String(nextId++);\n  const item = { id, name, description: description || '', createdAt: new Date().toISOString() };\n  items.set(id, item);\n  res.status(201).json(item);\n});\n\napp.put('\u002Fapi\u002Fitems\u002F:id', (req, res) => {\n  if (!items.has(req.params.id)) return res.status(404).json({ error: 'Not found' });\n  const item = { ...req.body, id: req.params.id, updatedAt: new Date().toISOString() };\n  items.set(req.params.id, item);\n  res.json(item);\n});\n\napp.delete('\u002Fapi\u002Fitems\u002F:id', (req, res) => {\n  if (!items.has(req.params.id)) return res.status(404).json({ error: 'Not found' });\n  items.delete(req.params.id);\n  res.status(204).end();\n});\n\n\u002F\u002F Error handler\napp.use((err, req, res, next) => {\n  console.error(err.stack);\n  res.status(500).json({ error: 'Internal server error' });\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => console.log(`API running on http:\u002F\u002Flocalhost:${PORT}`));\n```\n\n### Setup\n\n```bash\nmkdir my-api && cd my-api\nnpm init -y\nnpm install express\nnode server.js\n```\n\n## Debugging Patterns\n\n### Check if port is in use\n\n```bash\n# Linux\u002FmacOS\nlsof -i :3000\n# or\nss -tlnp | grep 3000\n\n# Kill process on port\nkill $(lsof -t -i :3000)\n```\n\n### Test CORS\n\n```bash\n# Preflight request\ncurl -s -X OPTIONS https:\u002F\u002Fapi.example.com\u002Fusers \\\n  -H \"Origin: http:\u002F\u002Flocalhost:3000\" \\\n  -H \"Access-Control-Request-Method: POST\" \\\n  -H \"Access-Control-Request-Headers: Content-Type\" \\\n  -I\n```\n\n### Watch for response time regressions\n\n```bash\n# Quick benchmark (10 requests)\nfor i in $(seq 1 10); do\n  curl -s -o \u002Fdev\u002Fnull -w \"%{time_total}\\n\" http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fusers\ndone | awk '{sum+=$1; if($1>max)max=$1} END {printf \"Avg: %.3fs, Max: %.3fs\\n\", sum\u002FNR, max}'\n```\n\n### Inspect JWT tokens\n\n```bash\n# Decode JWT payload (no verification)\necho \"$TOKEN\" | cut -d. -f2 | base64 -d 2>\u002Fdev\u002Fnull | jq .\n```\n\n## Tips\n\n- Use `jq` for JSON response processing: `curl -s url | jq '.items[] | {id, name}'`\n- Set `Content-Type` header on every request with a body - missing it causes silent 400s\n- Use `-w '\\n'` with curl to ensure output ends with a newline\n- For large response bodies, pipe to `jq -C . | less -R` for colored paging\n- Test error paths: invalid JSON, missing fields, wrong types, unauthorized, not found\n- For WebSocket testing: `npx wscat -c ws:\u002F\u002Flocalhost:3000\u002Fws`\n","# API Development\n\nBuild, test, document, and debug HTTP APIs from the command line. Covers the full API lifecycle: scaffolding endpoints, testing with curl, generating OpenAPI docs, mocking services, and debugging.\n\n## When to Use\n\n- Scaffolding new REST or GraphQL endpoints\n- Testing APIs with curl or scripts\n- Generating or validating OpenAPI\u002FSwagger specs\n- Mocking external APIs for development\n- Debugging HTTP request\u002Fresponse issues\n- Load testing endpoints\n\n## Testing APIs with curl\n\n### GET requests\n\n```bash\n# Basic GET\ncurl -s https:\u002F\u002Fapi.example.com\u002Fusers | jq .\n\n# With headers\ncurl -s -H \"Authorization: Bearer $TOKEN\" \\\n  -H \"Accept: application\u002Fjson\" \\\n  https:\u002F\u002Fapi.example.com\u002Fusers | jq .\n\n# With query params\ncurl -s \"https:\u002F\u002Fapi.example.com\u002Fusers?page=2&limit=10\" | jq .\n\n# Show response headers too\ncurl -si https:\u002F\u002Fapi.example.com\u002Fusers\n```\n\n### POST\u002FPUT\u002FPATCH\u002FDELETE\n\n```bash\n# POST JSON\ncurl -s -X POST https:\u002F\u002Fapi.example.com\u002Fusers \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $TOKEN\" \\\n  -d '{\"name\": \"Alice\", \"email\": \"alice@example.com\"}' | jq .\n\n# PUT (full replace)\ncurl -s -X PUT https:\u002F\u002Fapi.example.com\u002Fusers\u002F123 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"name\": \"Alice Updated\", \"email\": \"alice@example.com\"}' | jq .\n\n# PATCH (partial update)\ncurl -s -X PATCH https:\u002F\u002Fapi.example.com\u002Fusers\u002F123 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"name\": \"Alice V2\"}' | jq .\n\n# DELETE\ncurl -s -X DELETE https:\u002F\u002Fapi.example.com\u002Fusers\u002F123\n\n# POST form data\ncurl -s -X POST https:\u002F\u002Fapi.example.com\u002Fupload \\\n  -F \"file=@document.pdf\" \\\n  -F \"description=My document\"\n```\n\n### Debug requests\n\n```bash\n# Verbose output (see full request\u002Fresponse)\ncurl -v https:\u002F\u002Fapi.example.com\u002Fhealth 2>&1\n\n# Show only response headers\ncurl -sI https:\u002F\u002Fapi.example.com\u002Fhealth\n\n# Show timing breakdown\ncurl -s -o \u002Fdev\u002Fnull -w \"DNS: %{time_namelookup}s\\nConnect: %{time_connect}s\\nTLS: %{time_appconnect}s\\nFirst byte: %{time_starttransfer}s\\nTotal: %{time_total}s\\n\" https:\u002F\u002Fapi.example.com\u002Fhealth\n\n# Follow redirects\ncurl -sL https:\u002F\u002Fapi.example.com\u002Fold-endpoint\n\n# Save response to file\ncurl -s -o response.json https:\u002F\u002Fapi.example.com\u002Fdata\n```\n\n## API Test Scripts\n\n### Bash test runner\n\n```bash\n#!\u002Fbin\u002Fbash\n# api-test.sh - Simple API test runner\nBASE_URL=\"${1:-http:\u002F\u002Flocalhost:3000}\"\nPASS=0\nFAIL=0\n\nassert_status() {\n  local method=\"$1\" url=\"$2\" expected=\"$3\" body=\"$4\"\n  local args=(-s -o \u002Fdev\u002Fnull -w \"%{http_code}\" -X \"$method\")\n  if [ -n \"$body\" ]; then\n    args+=(-H \"Content-Type: application\u002Fjson\" -d \"$body\")\n  fi\n  local status\n  status=$(curl \"${args[@]}\" \"$BASE_URL$url\")\n  if [ \"$status\" = \"$expected\" ]; then\n    echo \"PASS: $method $url -> $status\"\n    ((PASS++))\n  else\n    echo \"FAIL: $method $url -> $status (expected $expected)\"\n    ((FAIL++))\n  fi\n}\n\nassert_json() {\n  local url=\"$1\" jq_expr=\"$2\" expected=\"$3\"\n  local actual\n  actual=$(curl -s \"$BASE_URL$url\" | jq -r \"$jq_expr\")\n  if [ \"$actual\" = \"$expected\" ]; then\n    echo \"PASS: GET $url | jq '$jq_expr' = $expected\"\n    ((PASS++))\n  else\n    echo \"FAIL: GET $url | jq '$jq_expr' = $actual (expected $expected)\"\n    ((FAIL++))\n  fi\n}\n\n# Health check\nassert_status GET \u002Fhealth 200\n\n# CRUD tests\nassert_status POST \u002Fapi\u002Fusers 201 '{\"name\":\"Test\",\"email\":\"test@test.com\"}'\nassert_status GET \u002Fapi\u002Fusers 200\nassert_json \u002Fapi\u002Fusers '.[-1].name' 'Test'\nassert_status DELETE \u002Fapi\u002Fusers\u002F1 204\n\n# Auth tests\nassert_status GET \u002Fapi\u002Fadmin 401\nassert_status GET \u002Fapi\u002Fadmin 403  # with wrong role\n\necho \"\"\necho \"Results: $PASS passed, $FAIL failed\"\n[ \"$FAIL\" -eq 0 ] && exit 0 || exit 1\n```\n\n### Python test runner\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"api_test.py - API integration test suite.\"\"\"\nimport json, sys, urllib.request, urllib.error\n\nBASE = sys.argv[1] if len(sys.argv) > 1 else \"http:\u002F\u002Flocalhost:3000\"\nPASS = FAIL = 0\n\ndef request(method, path, body=None, headers=None):\n    \"\"\"Make an HTTP request, return (status, body_dict, headers).\"\"\"\n    url = f\"{BASE}{path}\"\n    data = json.dumps(body).encode() if body else None\n    hdrs = {\"Content-Type\": \"application\u002Fjson\", \"Accept\": \"application\u002Fjson\"}\n    if headers:\n        hdrs.update(headers)\n    req = urllib.request.Request(url, data=data, headers=hdrs, method=method)\n    try:\n        resp = urllib.request.urlopen(req)\n        body = json.loads(resp.read().decode()) if resp.read() else None\n    except urllib.error.HTTPError as e:\n        return e.code, None, dict(e.headers)\n    return resp.status, body, dict(resp.headers)\n\ndef test(name, fn):\n    \"\"\"Run a test function, track pass\u002Ffail.\"\"\"\n    global PASS, FAIL\n    try:\n        fn()\n        print(f\"  PASS: {name}\")\n        PASS += 1\n    except AssertionError as e:\n        print(f\"  FAIL: {name} - {e}\")\n        FAIL += 1\n\ndef assert_eq(actual, expected, msg=\"\"):\n    assert actual == expected, f\"got {actual}, expected {expected}. {msg}\"\n\n# --- Tests ---\nprint(f\"Testing {BASE}\\n\")\n\ntest(\"GET \u002Fhealth returns 200\", lambda: (\n    assert_eq(request(\"GET\", \"\u002Fhealth\")[0], 200)\n))\n\ntest(\"POST \u002Fapi\u002Fusers creates user\", lambda: (\n    assert_eq(request(\"POST\", \"\u002Fapi\u002Fusers\", {\"name\": \"Test\", \"email\": \"t@t.com\"})[0], 201)\n))\n\ntest(\"GET \u002Fapi\u002Fusers returns array\", lambda: (\n    assert_eq(type(request(\"GET\", \"\u002Fapi\u002Fusers\")[1]), list)\n))\n\ntest(\"GET \u002Fapi\u002Fnotfound returns 404\", lambda: (\n    assert_eq(request(\"GET\", \"\u002Fapi\u002Fnotfound\")[0], 404)\n))\n\nprint(f\"\\nResults: {PASS} passed, {FAIL} failed\")\nsys.exit(0 if FAIL == 0 else 1)\n```\n\n## OpenAPI Spec Generation\n\n### Generate from existing endpoints\n\n```bash\n# Scaffold an OpenAPI 3.0 spec from curl responses\n# Run this, then fill in the details\ncat > openapi.yaml \u003C\u003C 'EOF'\nopenapi: \"3.0.3\"\ninfo:\n  title: My API\n  version: \"1.0.0\"\n  description: API description here\nservers:\n  - url: http:\u002F\u002Flocalhost:3000\n    description: Local development\npaths:\n  \u002Fhealth:\n    get:\n      summary: Health check\n      responses:\n        \"200\":\n          description: Service is healthy\n          content:\n            application\u002Fjson:\n              schema:\n                type: object\n                properties:\n                  status:\n                    type: string\n                    example: ok\n  \u002Fapi\u002Fusers:\n    get:\n      summary: List users\n      parameters:\n        - name: page\n          in: query\n          schema:\n            type: integer\n            default: 1\n        - name: limit\n          in: query\n          schema:\n            type: integer\n            default: 20\n      responses:\n        \"200\":\n          description: List of users\n          content:\n            application\u002Fjson:\n              schema:\n                type: array\n                items:\n                  $ref: \"#\u002Fcomponents\u002Fschemas\u002FUser\"\n    post:\n      summary: Create user\n      requestBody:\n        required: true\n        content:\n          application\u002Fjson:\n            schema:\n              $ref: \"#\u002Fcomponents\u002Fschemas\u002FCreateUser\"\n      responses:\n        \"201\":\n          description: User created\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: \"#\u002Fcomponents\u002Fschemas\u002FUser\"\n        \"400\":\n          description: Validation error\n  \u002Fapi\u002Fusers\u002F{id}:\n    get:\n      summary: Get user by ID\n      parameters:\n        - name: id\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        \"200\":\n          description: User details\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: \"#\u002Fcomponents\u002Fschemas\u002FUser\"\n        \"404\":\n          description: Not found\ncomponents:\n  schemas:\n    User:\n      type: object\n      properties:\n        id:\n          type: string\n        name:\n          type: string\n        email:\n          type: string\n          format: email\n        createdAt:\n          type: string\n          format: date-time\n    CreateUser:\n      type: object\n      required:\n        - name\n        - email\n      properties:\n        name:\n          type: string\n        email:\n          type: string\n          format: email\n  securitySchemes:\n    bearerAuth:\n      type: http\n      scheme: bearer\n      bearerFormat: JWT\nEOF\n```\n\n### Validate OpenAPI spec\n\n```bash\n# Using npx (no install needed)\nnpx @redocly\u002Fcli lint openapi.yaml\n\n# Quick check: is the YAML valid?\npython3 -c \"import yaml; yaml.safe_load(open('openapi.yaml'))\" && echo \"Valid YAML\"\n```\n\n## Mock Server\n\n### Quick mock with Python\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"mock_server.py - Lightweight API mock from OpenAPI-like config.\"\"\"\nimport json, http.server, re, sys\n\nPORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080\n\n# Define mock routes: (method, path_pattern) -> response\nROUTES = {\n    (\"GET\", \"\u002Fhealth\"): {\"status\": 200, \"body\": {\"status\": \"ok\"}},\n    (\"GET\", \"\u002Fapi\u002Fusers\"): {\"status\": 200, \"body\": [\n        {\"id\": \"1\", \"name\": \"Alice\", \"email\": \"alice@example.com\"},\n        {\"id\": \"2\", \"name\": \"Bob\", \"email\": \"bob@example.com\"},\n    ]},\n    (\"POST\", \"\u002Fapi\u002Fusers\"): {\"status\": 201, \"body\": {\"id\": \"3\", \"name\": \"Created\"}},\n    (\"GET\", r\"\u002Fapi\u002Fusers\u002F\\w+\"): {\"status\": 200, \"body\": {\"id\": \"1\", \"name\": \"Alice\"}},\n    (\"DELETE\", r\"\u002Fapi\u002Fusers\u002F\\w+\"): {\"status\": 204, \"body\": None},\n}\n\nclass MockHandler(http.server.BaseHTTPRequestHandler):\n    def _handle(self):\n        for (method, pattern), response in ROUTES.items():\n            if self.command == method and re.fullmatch(pattern, self.path.split('?')[0]):\n                self.send_response(response[\"status\"])\n                if response[\"body\"] is not None:\n                    self.send_header(\"Content-Type\", \"application\u002Fjson\")\n                    self.end_headers()\n                    self.wfile.write(json.dumps(response[\"body\"]).encode())\n                else:\n                    self.end_headers()\n                return\n        self.send_response(404)\n        self.send_header(\"Content-Type\", \"application\u002Fjson\")\n        self.end_headers()\n        self.wfile.write(json.dumps({\"error\": \"Not found\"}).encode())\n\n    do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _handle\n\n    def log_message(self, fmt, *args):\n        print(f\"{self.command} {self.path} -> {args[1] if len(args) > 1 else '?'}\")\n\nprint(f\"Mock server on http:\u002F\u002Flocalhost:{PORT}\")\nhttp.server.HTTPServer((\"\", PORT), MockHandler).serve_forever()\n```\n\nRun: `python3 mock_server.py 8080`\n\n## Node.js Express Scaffolding\n\n### Minimal REST API\n\n```javascript\n\u002F\u002F server.js - Minimal Express REST API\nconst express = require('express');\nconst app = express();\napp.use(express.json());\n\n\u002F\u002F In-memory store\nconst items = new Map();\nlet nextId = 1;\n\n\u002F\u002F CRUD endpoints\napp.get('\u002Fapi\u002Fitems', (req, res) => {\n  const { page = 1, limit = 20 } = req.query;\n  const all = [...items.values()];\n  const start = (page - 1) * limit;\n  res.json({ items: all.slice(start, start + +limit), total: all.length });\n});\n\napp.get('\u002Fapi\u002Fitems\u002F:id', (req, res) => {\n  const item = items.get(req.params.id);\n  if (!item) return res.status(404).json({ error: 'Not found' });\n  res.json(item);\n});\n\napp.post('\u002Fapi\u002Fitems', (req, res) => {\n  const { name, description } = req.body;\n  if (!name) return res.status(400).json({ error: 'name required' });\n  const id = String(nextId++);\n  const item = { id, name, description: description || '', createdAt: new Date().toISOString() };\n  items.set(id, item);\n  res.status(201).json(item);\n});\n\napp.put('\u002Fapi\u002Fitems\u002F:id', (req, res) => {\n  if (!items.has(req.params.id)) return res.status(404).json({ error: 'Not found' });\n  const item = { ...req.body, id: req.params.id, updatedAt: new Date().toISOString() };\n  items.set(req.params.id, item);\n  res.json(item);\n});\n\napp.delete('\u002Fapi\u002Fitems\u002F:id', (req, res) => {\n  if (!items.has(req.params.id)) return res.status(404).json({ error: 'Not found' });\n  items.delete(req.params.id);\n  res.status(204).end();\n});\n\n\u002F\u002F Error handler\napp.use((err, req, res, next) => {\n  console.error(err.stack);\n  res.status(500).json({ error: 'Internal server error' });\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => console.log(`API running on http:\u002F\u002Flocalhost:${PORT}`));\n```\n\n### Setup\n\n```bash\nmkdir my-api && cd my-api\nnpm init -y\nnpm install express\nnode server.js\n```\n\n## Debugging Patterns\n\n### Check if port is in use\n\n```bash\n# Linux\u002FmacOS\nlsof -i :3000\n# or\nss -tlnp | grep 3000\n\n# Kill process on port\nkill $(lsof -t -i :3000)\n```\n\n### Test CORS\n\n```bash\n# Preflight request\ncurl -s -X OPTIONS https:\u002F\u002Fapi.example.com\u002Fusers \\\n  -H \"Origin: http:\u002F\u002Flocalhost:3000\" \\\n  -H \"Access-Control-Request-Method: POST\" \\\n  -H \"Access-Control-Request-Headers: Content-Type\" \\\n  -I\n```\n\n### Watch for response time regressions\n\n```bash\n# Quick benchmark (10 requests)\nfor i in $(seq 1 10); do\n  curl -s -o \u002Fdev\u002Fnull -w \"%{time_total}\\n\" http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fusers\ndone | awk '{sum+=$1; if($1>max)max=$1} END {printf \"Avg: %.3fs, Max: %.3fs\\n\", sum\u002FNR, max}'\n```\n\n### Inspect JWT tokens\n\n```bash\n# Decode JWT payload (no verification)\necho \"$TOKEN\" | cut -d. -f2 | base64 -d 2>\u002Fdev\u002Fnull | jq .\n```\n\n## Tips\n\n- Use `jq` for JSON response processing: `curl -s url | jq '.items[] | {id, name}'`\n- Set `Content-Type` header on every request with a body - missing it causes silent 400s\n- Use `-w '\\n'` with curl to ensure output ends with a newline\n- For large response bodies, pipe to `jq -C . | less -R` for colored paging\n- Test error paths: invalid JSON, missing fields, wrong types, unauthorized, not found\n- For WebSocket testing: `npx wscat -c ws:\u002F\u002Flocalhost:3000\u002Fws`\n",{"name":5,"metadata":56,"description":7},{"clawdbot":57},{"os":58,"emoji":60,"requires":61},[42,59,44],"darwin","?",{"anyBins":62},[63,40,41],"curl","main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fgitgoodordietrying\u002Fapi-dev",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":72,"prompt":82,"zipAvailable":83},[73,76,79],{"tool":74,"command":75},"npx","npx skills add kbarbel640-del\u002Fskills --skill api-dev",{"tool":77,"command":78},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill api-dev",{"tool":80,"command":81},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill api-dev","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fgitgoodordietrying\u002Fapi-dev\u002FSKILL.md",true,[85],{"path":86,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":89,"sourceHtmlUrl":90},"_meta.json","REFERENCE","参考文档",286,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fgitgoodordietrying\u002Fapi-dev\u002F_meta.json",[92,120,145,165,171,189],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":101,"publishedAt":51},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[98],{"categoryNo":99,"categoryName":100,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000036","内容创作者",[102,103,33,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119],"crowd prompting","prompting","with","tokens","domain","world","prompts","operations","instructions","text","tool","system","improve","productivity","marketplace","https","content","ai agents",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":129,"publishedAt":51},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[126],{"categoryNo":127,"categoryName":128,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发",[130,33,131,132,133,134,46,135,136,137,138,139,140,141,142,143,144,108,38],"dilemm ai","arena","analyze","browser","openclaw agent","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":154,"publishedAt":51},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[151],{"categoryNo":152,"categoryName":153,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000021","资料检索与研究",[155,156,157,158,159,160,161,104,162,143,38,163,33,47,164],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","via",{"skillNo":166,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":170,"publishedAt":51},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[169],{"categoryNo":152,"categoryName":153,"taxonomyType":20,"taxonomyTypeDesc":21},[158,157,156,155,164,160,161,104,159,143,38,162,163,33,47],{"skillNo":172,"name":173,"nameZh":6,"description":174,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":175,"categories":176,"keywords":177,"publishedAt":51},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[178,179,180,181,182,44,183,42,184,185,186,187,188],"git","summary","git summary","commits","repository","status","contributors","true","quick","get","branches",{"skillNo":190,"name":191,"nameZh":6,"description":192,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":193,"categories":194,"keywords":199,"publishedAt":51},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[195,196],{"categoryNo":127,"categoryName":128,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":197,"categoryName":198,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000037","律师与法务",[200,201,202,203,104,204,205,64,206,163,207,208,209,210,211,117,212,213,214],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]