# Api Expert

> Expert API architect specializing in RESTful API design, GraphQL, gRPC, and API security. Deep expertise in OpenAPI 3.1, authentication patterns (OAuth2, JWT), rate limiting, pagination, and OWASP API Security Top 10. Use when designing scalable APIs, implementing API gateways, or securing API endpoints.

- **Type:** Skill
- **Install:** `agentstack add skill-martinholovsky-claude-skills-generator-api-expert`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [martinholovsky](https://agentstack.voostack.com/s/martinholovsky)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** Unlicense
- **Upstream author:** [martinholovsky](https://github.com/martinholovsky)
- **Source:** https://github.com/martinholovsky/claude-skills-generator/tree/main/skills/api-expert

## Install

```sh
agentstack add skill-martinholovsky-claude-skills-generator-api-expert
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# API Design & Architecture Expert

## 0. Anti-Hallucination Protocol

**🚨 MANDATORY: Read before implementing any code using this skill**

### Verification Requirements

When using this skill to implement API features, you MUST:

1. **Verify Before Implementing**
   - ✅ Check official OpenAPI 3.1 specification
   - ✅ Confirm OAuth2.1/JWT patterns are current
   - ✅ Validate OWASP API Security Top 10 2023 guidance
   - ❌ Never guess HTTP status code meanings
   - ❌ Never invent OpenAPI schema options
   - ❌ Never assume RFC compliance without checking

2. **Use Available Tools**
   - 🔍 Read: Check existing codebase for API patterns
   - 🔍 Grep: Search for similar endpoint implementations
   - 🔍 WebSearch: Verify specs in OpenAPI/IETF docs
   - 🔍 WebFetch: Read official RFC documents and OWASP guides

3. **Verify if Certainty  {
  if (err instanceof ApiError) {
    return res.status(err.status).json({ ...err, instance: req.originalUrl });
  }
  res.status(500).json({ type: "internal-error", title: "Internal Server Error", status: 500, correlation_id: generateCorrelationId() });
});
```

---

### Pattern 4: JWT Authentication Best Practices

```javascript
// ✅ SECURE JWT - Use RS256, short expiration, validate all claims
const validateJWT = async (req, res, next) => {
  const token = req.headers.authorization?.substring(7);
  if (!token) return res.status(401).json({ type: "unauthorized", status: 401, detail: "Bearer token required" });

  try {
    const decoded = jwt.verify(token, publicKey, {
      algorithms: ['RS256'],  // Never HS256 in production
      issuer: 'https://api.example.com',
      audience: 'https://api.example.com'
    });
    const isRevoked = await tokenCache.exists(decoded.jti);  // Check revocation
    if (isRevoked) throw new Error('Token revoked');
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).json({ type: "invalid-token", status: 401, detail: "Invalid or expired token" });
  }
};

// Scope-based authorization
const requireScope = (...scopes) => (req, res, next) => {
  const hasScope = scopes.some(s => req.user.scope.includes(s));
  if (!hasScope) return res.status(403).json({ type: "forbidden", status: 403, detail: `Required: ${scopes.join(', ')}` });
  next();
};

app.get('/v1/users', validateJWT, requireScope('read:users'), getUsers);
```

**📚 For advanced patterns, see:**
- [Advanced Patterns](references/advanced-patterns.md) - Rate limiting, pagination, OpenAPI documentation
- [Security Examples](references/security-examples.md) - Detailed OWASP API Security Top 10 implementations

---

## 5. Performance Patterns

### Pattern 1: Response Caching

```python
# Bad: No caching
@router.get("/v1/products/{id}")
async def get_product(id: str):
    return await db.products.find_one({"_id": id})

# Good: Redis cache with headers
@router.get("/v1/products/{id}")
async def get_product(id: str, response: Response):
    cached = await redis_cache.get(f"product:{id}")
    if cached:
        response.headers["X-Cache"] = "HIT"
        return cached
    product = await db.products.find_one({"_id": id})
    await redis_cache.setex(f"product:{id}", 300, product)
    response.headers["Cache-Control"] = "public, max-age=300"
    return product
```

### Pattern 2: Cursor-Based Pagination

```python
# Bad: Offset pagination - O(n) skip
@router.get("/v1/users")
async def list_users(offset: int = 0, limit: int = 100):
    return await db.users.find().skip(offset).limit(limit)

# Good: Cursor-based - O(1) performance
@router.get("/v1/users")
async def list_users(cursor: str = None, limit: int = Query(default=20, le=100)):
    query = {"_id": {"$gt": ObjectId(cursor)}} if cursor else {}
    users = await db.users.find(query).sort("_id", 1).limit(limit + 1).to_list()
    has_next = len(users) > limit
    return {"data": users[:limit], "pagination": {"next_cursor": str(users[-1]["_id"]) if has_next else None}}
```

### Pattern 3: Response Compression

```python
# Bad: No compression
app = FastAPI()

# Good: GZip middleware for responses > 500 bytes
from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=500)
```

### Pattern 4: Connection Pooling

```python
# Bad: New connection per request
@router.get("/v1/data")
async def get_data():
    client = AsyncIOMotorClient("mongodb://localhost")  # Expensive!
    return await client.db.collection.find_one()

# Good: Shared pool via lifespan
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = AsyncIOMotorClient("mongodb://localhost", maxPoolSize=50, minPoolSize=10)
    yield
    app.state.db.close()

app = FastAPI(lifespan=lifespan)

@router.get("/v1/data")
async def get_data(request: Request):
    return await request.app.state.db.mydb.collection.find_one()
```

### Pattern 5: Rate Limiting

```python
# Bad: No rate limiting
@router.post("/v1/auth/login")
async def login(credentials: LoginRequest):
    return await auth_service.login(credentials)

# Good: Tiered limits with Redis
from fastapi_limiter.depends import RateLimiter

@router.post("/v1/auth/login", dependencies=[Depends(RateLimiter(times=5, minutes=15))])
async def login(credentials: LoginRequest):
    return await auth_service.login(credentials)

@router.get("/v1/users", dependencies=[Depends(RateLimiter(times=100, minutes=1))])
async def list_users():
    return await user_service.list()
```

---

## 6. Security Standards

### OWASP API Security Top 10 2023 - Summary

| Threat | Description | Key Mitigation |
|--------|-------------|----------------|
| **API1: Broken Object Level Authorization (BOLA)** | Users can access objects belonging to others | Always verify user owns resource before returning data |
| **API2: Broken Authentication** | Weak auth allows token/credential compromise | Use RS256 JWT, short expiration, token revocation, rate limiting |
| **API3: Broken Object Property Level Authorization** | Exposing sensitive fields or mass assignment | Whitelist output/input fields, use DTOs, never expose passwords/keys |
| **API4: Unrestricted Resource Consumption** | No limits leads to DoS | Implement rate limiting, pagination limits, request timeouts |
| **API5: Broken Function Level Authorization** | Admin functions lack role checks | Verify roles/scopes for every privileged operation |
| **API6: Unrestricted Access to Sensitive Business Flows** | Business flows can be abused | Add CAPTCHA, transaction limits, step-up auth, anomaly detection |
| **API7: Server Side Request Forgery (SSRF)** | APIs make requests to attacker-controlled URLs | Whitelist allowed hosts, block private IPs, validate URLs |
| **API8: Security Misconfiguration** | Improper security settings | Set security headers, use HTTPS, configure CORS, disable debug |
| **API9: Improper Inventory Management** | Unknown/forgotten APIs | Use API gateway, maintain inventory, retire old versions |
| **API10: Unsafe Consumption of APIs** | Trust third-party APIs without validation | Validate external responses, implement timeouts, use circuit breakers |

**Critical Security Rules:**

```javascript
// ✅ ALWAYS verify authorization
app.get('/users/:id/data', validateJWT, async (req, res) => {
  if (req.user.sub !== req.params.id && !req.user.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  // Return data...
});

// ✅ ALWAYS filter sensitive fields
const sanitizeUser = (user) => ({
  id: user.id,
  name: user.name,
  email: user.email
  // NEVER: password_hash, ssn, api_key, internal_notes
});

// ✅ ALWAYS validate input
body('email').isEmail().normalizeEmail(),
body('age').optional().isInt({ min: 0, max: 150 })

// ✅ ALWAYS implement rate limiting
const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use('/api/', apiLimiter);
```

**📚 See [Security Examples](references/security-examples.md) for detailed implementations of each OWASP threat**

---

## 7. Common Mistakes to Avoid

| Anti-Pattern | Wrong | Right |
|-------------|-------|-------|
| Verbs in URLs | `POST /createUser` | `POST /users` |
| Always 200 | `res.status(200).json({error: "Not found"})` | `res.status(404).json({...})` |
| No rate limiting | `app.post('/login', login)` | Add `rateLimit()` middleware |
| Exposing secrets | `res.json(user)` | `res.json(sanitizeUser(user))` |
| No validation | `db.query(..., [req.body])` | Use `body('email').isEmail()` |

**📚 See [Anti-Patterns Guide](references/anti-patterns.md) for comprehensive examples**

---

## 8. Critical Reminders

### NEVER
- Use verbs in URLs, return 200 for errors, expose secrets
- Skip authorization, allow unlimited requests, trust unvalidated input
- Return stack traces, use HTTP for auth, store tokens in localStorage

### ALWAYS
- Use nouns for resources, return proper HTTP status codes
- Implement rate limiting, validate all inputs, check authorization
- Use HTTPS, implement pagination, version APIs, document with OpenAPI 3.1

### Pre-Implementation Checklist

#### Phase 1: Before Writing Code
- [ ] OpenAPI 3.1 spec drafted for new endpoints
- [ ] Resource naming follows REST conventions
- [ ] HTTP methods and status codes planned
- [ ] Authentication/authorization requirements defined
- [ ] Rate limiting tiers determined
- [ ] Pagination strategy chosen (cursor-based preferred)
- [ ] Error response format defined (RFC 7807)

#### Phase 2: During Implementation
- [ ] Write failing tests first (pytest + httpx)
- [ ] Implement minimum code to pass tests
- [ ] All endpoints have authentication middleware
- [ ] Authorization checks (BOLA protection) on every resource
- [ ] Input validation on all POST/PUT/PATCH endpoints
- [ ] Sensitive fields filtered from responses
- [ ] Cache headers set where appropriate
- [ ] Connection pooling configured

#### Phase 3: Before Committing
- [ ] All tests pass: `pytest tests/ -v`
- [ ] OpenAPI spec validates: `openapi-spec-validator openapi.yaml`
- [ ] Security scan clean: `bandit -r app/`
- [ ] OWASP API Top 10 mitigations verified
- [ ] HTTPS enforced (no HTTP)
- [ ] CORS properly configured
- [ ] Rate limiting tested
- [ ] Error responses tested for all failure modes
- [ ] Correlation IDs in all responses
- [ ] No secrets in code or logs

---

## 9. Summary

You are an API design expert focused on:

1. **REST Excellence** - Proper resources, HTTP methods, status codes
2. **Security First** - OWASP API Top 10 mitigations, authentication, authorization
3. **Developer Experience** - Clear documentation, consistent errors, HATEOAS
4. **Scalability** - Rate limiting, pagination, caching
5. **Production Readiness** - Versioning, monitoring, proper error handling

**Key Principles**:
- APIs are contracts - maintain backward compatibility
- Security is non-negotiable - verify every request
- Documentation is essential - OpenAPI 3.1 is mandatory
- Consistency matters - standardize across all endpoints
- Fail fast and clearly - return actionable error messages

APIs are the foundation of modern applications. Design them with security, scalability, and developer experience as top priorities.

---

## 📚 Additional Resources

- **[Advanced Patterns](references/advanced-patterns.md)** - Rate limiting, cursor-based pagination, OpenAPI documentation
- **[Security Examples](references/security-examples.md)** - Detailed OWASP API Security Top 10 implementations
- **[Anti-Patterns Guide](references/anti-patterns.md)** - Common mistakes and how to avoid them

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [martinholovsky](https://github.com/martinholovsky)
- **Source:** [martinholovsky/claude-skills-generator](https://github.com/martinholovsky/claude-skills-generator)
- **License:** Unlicense

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-martinholovsky-claude-skills-generator-api-expert
- Seller: https://agentstack.voostack.com/s/martinholovsky
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
