Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/generating-rest-apis

@820dfc8
Run it yourself

Generate complete REST API implementations from OpenAPI specifications or database schemas. Use when generating RESTful API implementations. Trigger with phrases like "generate REST API", "create RESTful API", or "build REST endpoints".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/generating-rest-apis

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesexamples.md

≈1.8k tokens on demand. Your agent reads this file only when SKILL.md points to it.

REST API Generator Examples

Express CRUD Endpoints

// routes/users.js
const express = require('express');
const router = express.Router();

// GET /users - List with pagination, filtering, sorting
router.get('/', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = Math.min(parseInt(req.query.limit) || 20, 100);
  const offset = (page - 1) * limit;
  const sort = req.query.sort || '-createdAt'; // '-' prefix = descending

  const where = {};
  if (req.query.status) where.status = req.query.status;
  if (req.query.search) where.name = { $iLike: `%${req.query.search}%` };

  const [data, total] = await Promise.all([
    db.users.findAll({ where, limit, offset, order: parseSortParam(sort) }),
    db.users.count({ where }),
  ]);

  res.json({ data, pagination: { page, limit, total, pages: Math.ceil(total / limit) } });
});

// GET /users/:id
router.get('/:id', async (req, res) => {
  const user = await db.users.findById(req.params.id);
  if (!user) throw new NotFoundError('User', req.params.id);

  const fields = req.query.fields?.split(',');
  res.json(fields ? pick(user, fields) : user);
});

// POST /users
router.post('/', authenticateToken, async (req, res) => {
  const data = CreateUserSchema.parse(req.body);
  const user = await db.users.create(data);
  res.status(201).json(user);
});

// PUT /users/:id
router.put('/:id', authenticateToken, async (req, res) => {
  const data = UpdateUserSchema.parse(req.body);
  const user = await db.users.findById(req.params.id);
  if (!user) throw new NotFoundError('User', req.params.id);
  const updated = await db.users.update(req.params.id, data);
  res.json(updated);
});

// DELETE /users/:id
router.delete('/:id', authenticateToken, requireRole('admin'), async (req, res) => {
  const user = await db.users.findById(req.params.id);
  if (!user) throw new NotFoundError('User', req.params.id);
  await db.users.destroy(req.params.id);
  res.status(204).end();
});

app.use('/api/users', router);

Request Validation (Zod)

// middleware/validate.js
const { z } = require('zod');

const CreateUserSchema = z.object({
  name: z.string().min(1).max(255),
  email: z.string().email(),
  role: z.enum(['user', 'admin']).default('user'),
});

const UpdateUserSchema = z.object({
  name: z.string().min(1).max(255).optional(),
  email: z.string().email().optional(),
  status: z.enum(['active', 'inactive', 'suspended']).optional(),
});

function validate(schema) {
  return (req, res, next) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      return res.status(400).json({
        type: 'https://api.example.com/errors/validation',
        title: 'Validation Error',
        status: 400,
        errors: result.error.issues.map(i => ({
          field: i.path.join('.'), message: i.message, code: i.code,
        })),
      });
    }
    req.body = result.data;
    next();
  };
}

router.post('/', authenticateToken, validate(CreateUserSchema), createUser);

FastAPI Implementation (Python)

from fastapi import FastAPI, Query, HTTPException
from pydantic import BaseModel, EmailStr
from typing import Optional

app = FastAPI()

class CreateUser(BaseModel):
    name: str
    email: EmailStr
    role: str = "user"

class UserResponse(BaseModel):
    id: str
    name: str
    email: str
    status: str

@app.get("/users", response_model=dict)
async def list_users(
    page: int = Query(1, ge=1),
    limit: int = Query(20, ge=1, le=100),
    status: Optional[str] = None,
    sort: str = "-created_at",
):
    offset = (page - 1) * limit
    users = await db.users.find(status=status, limit=limit, offset=offset, sort=sort)
    total = await db.users.count(status=status)
    return {"data": users, "pagination": {"page": page, "limit": limit, "total": total}}

@app.post("/users", status_code=201, response_model=UserResponse)
async def create_user(user: CreateUser):
    return await db.users.create(user.dict())

@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: str):
    user = await db.users.find_by_id(user_id)
    if not user:
        raise HTTPException(status_code=404, detail=f"User '{user_id}' not found")
    return user

@app.delete("/users/{user_id}", status_code=204)
async def delete_user(user_id: str):
    await db.users.delete(user_id)

curl: CRUD Operations

# List with pagination and filtering
curl "http://localhost:3000/api/users?page=1&limit=10&status=active&sort=-createdAt"
# {"data":[...],"pagination":{"page":1,"limit":10,"total":42,"pages":5}}

# Get with field selection
curl "http://localhost:3000/api/users/usr_123?fields=id,name,email"
# {"id":"usr_123","name":"Alice","email":"alice@example.com"}

# Create
curl -X POST http://localhost:3000/api/users \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice Smith","email":"alice@example.com","role":"user"}'
# 201 {"id":"usr_abc","name":"Alice Smith","email":"alice@example.com","status":"active"}

# Update
curl -X PUT http://localhost:3000/api/users/usr_abc \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice Johnson"}'
# {"id":"usr_abc","name":"Alice Johnson",...}

# Delete
curl -X DELETE http://localhost:3000/api/users/usr_abc \
  -H "Authorization: Bearer $TOKEN"
# 204 No Content

# Validation error
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" -d '{"name":"","email":"bad"}'
# 400 {"errors":[{"field":"name","message":"Too short"},{"field":"email","message":"Invalid email"}]}

Integration Tests

describe('Users API', () => {
  it('lists users with pagination', async () => {
    const res = await request(app).get('/api/users?page=1&limit=5');
    expect(res.status).toBe(200);
    expect(res.body.data.length).toBeLessThanOrEqual(5);
    expect(res.body.pagination).toMatchObject({ page: 1, limit: 5 });
  });

  it('creates user', async () => {
    const res = await request(app).post('/api/users')
      .set('Authorization', `Bearer ${token}`)
      .send({ name: 'Test', email: 'test@example.com' });
    expect(res.status).toBe(201);
    expect(res.body.id).toMatch(/^usr_/);
  });

  it('returns 404 for missing user', async () => {
    const res = await request(app).get('/api/users/nonexistent');
    expect(res.status).toBe(404);
  });

  it('returns 401 without auth', async () => {
    const res = await request(app).post('/api/users').send({ name: 'X', email: 'x@y.com' });
    expect(res.status).toBe(401);
  });
});

Sort Parameter Parser

function parseSortParam(sort) {
  return sort.split(',').map(field => {
    if (field.startsWith('-')) return [field.slice(1), 'DESC'];
    return [field, 'ASC'];
  });
}
// "-createdAt,name" -> [['createdAt', 'DESC'], ['name', 'ASC']]

Tons of Skills by Intent Solutions | jeremylongshore.com

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides a comprehensive framework for generating REST API implementations using various languages and frameworks. It utilizes standard development tools and retrieves configuration data from the author's verified domain.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 820dfc8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated last month
What it can do
Reads files Edits files Runs commands
version
1.24.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
[
  "api",
  "database",
  "rest-apis"
]
All 6 allowed tools
ReadWriteEditGrepGlobBash(api:rest-*)
Other metadata
compatibility
Designed for Claude Code

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/generating-rest-apis