stredne pokročilý

API Endpoint generátor

Generovanie REST API endpointov s validáciou, error handling a dokumentáciou

Programovanie
ChatGPT, Claude, Cursor, GitHub Copilot
#api#rest#nodejs#express#validácia

API Endpoint generátor

Definícia promptu

Špecializovaný prompt pre generovanie REST API endpointov s kompletnou štruktúrou vrátane validácie, error handling a dokumentácie pre moderné backend aplikácie.

Primárne využitie

Hlavné aplikácie

  • generovanie CRUD operácií pre databázové entity
  • vytváranie RESTful API endpointov
  • implementácia authentifikácie a autorizácie
  • middleware a error handling

Sekundárne scenáre

  • GraphQL resolver generovanie
  • API dokumentácia a testing
  • rate limiting a caching
  • microservices komunikácia

Štruktúra promptu

Základná šablóna

Vytvor REST API endpoint pre [entity] s nasledujúcimi špecifikáciami:

Entity: [detailný popis entity a vlastností]
Database: [databázový systém a ORM]
Framework: [backend framework]
Auth: [autentifikačná metóda]

Požiadavky:
- Kompletná CRUD operácia (Create, Read, Update, Delete)
- Input validácia a sanitization
- Error handling a status codes
- API dokumentácia
- Security best practices

Rozšírená verzia

Vytvor komplexný REST API endpoint pre [entity] s nasledujúcimi špecifikáciami:

Entity Detail:
- Názov: [entity name]
- Vlastnosti: [list of properties s types]
- Relationships: [foreign keys a asociácie]
- Business logic: [špecifické pravidlá a validácie]

Technical Stack:
- Backend: [Node.js/Python/Java/etc]
- Framework: [Express/FastAPI/Spring/etc]
- Database: [PostgreSQL/MongoDB/etc]
- ORM: [Prisma/SQLAlchemy/Hibernate/etc]
- Validation: [Joi/Pydantic/etc]

Authentication & Authorization:
- Method: [JWT/OAuth2/API Key]
- Roles: [user/admin/moderator]
- Permissions: [specific permissions pre endpoint]
- Rate limiting: [requests per minute]

Endpoints Required:
1. GET /api/[entity] - List všetkých záznamov s pagination
2. GET /api/[entity]/:id - Detail jedného záznamu
3. POST /api/[entity] - Vytvorenie nového záznamu
4. PUT /api/[entity]/:id - Update existujúceho záznamu
5. DELETE /api/[entity]/:id - Vymazanie záznamu

Validation Rules:
- Required fields: [list]
- Format validation: [email, phone, atď.]
- Business rules: [custom validácie]
- Error messages: [user-friendly messages]

Error Handling:
- Status codes: [400, 401, 403, 404, 500]
- Error format: [consistent error response structure]
- Logging: [error logging strategy]
- Monitoring: [health checks a metrics]

Security Requirements:
- Input sanitization
- SQL injection prevention
- XSS protection
- CORS configuration
- Rate limiting

Documentation:
- OpenAPI/Swagger spec
- Request/response examples
- Error response documentation
- Authentication examples

Testing:
- Unit tests pre business logic
- Integration tests pre endpoints
- API contract testing
- Load testing considerations

Output: Kompletný kód s:
1. Route definitions
2. Controller functions
3. Middleware functions
4. Validation schemas
5. Error handlers
6. Documentation
7. Test examples

Kľúčové parametre

Povinné parametre

  • entity - Hlavná databázová entita
  • framework - Backend framework a jazyk
  • database - Databázový systém

Voliteľné parametre

  • authentication - Metóda autentifikácie
  • validation - Validáčná knižnica
  • documentation - Formát dokumentácie
  • testing - Testovací framework

Najlepšie praktiky

Optimalizácia pre výsledky

  • Špecifikujte presnú štruktúru dát - lepšie generovanie
  • Definujte business pravidlá - relevantnejšia logika
  • Určte security requirements - bezpečnejší kód
  • Špecifikujte error handling - konzistentnejšie odpovede

Čo sa vyhnúť

  • Príliš všeobecné entity - menej presný kód
  • Ignorovanie validácie - bezpečnostné riziká
  • Chýbajúce error handling - zlý user experience
  • Neštandardné HTTP status codes - zlá API design

Príklady použitia

Základný príklad

Vstup:

Vytvor REST API endpoint pre User entity s nasledujúcimi špecifikáciami:

Entity: User s id, email, password, firstName, lastName, createdAt
Database: PostgreSQL s Prisma ORM
Framework: Node.js s Express
Auth: JWT token-based authentication

Požiadavky:
- Kompletná CRUD operácia
- Email validácia a password hashing
- Error handling s proper status codes
- Basic API dokumentácia

Výstup:

// routes/users.js
const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { PrismaClient } = require("@prisma/client");
const { body, validationResult } = require("express-validator");

const router = express.Router();
const prisma = new PrismaClient();

// Validation middleware
const validateUser = [
  body("email").isEmail().normalizeEmail(),
  body("password").isLength({ min: 6 }),
  body("firstName").notEmpty().trim(),
  body("lastName").notEmpty().trim(),
];

// GET /api/users - List all users (admin only)
router.get("/", async (req, res) => {
  try {
    const users = await prisma.user.findMany({
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        createdAt: true,
      },
    });
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
});

// GET /api/users/:id - Get user by ID
router.get("/:id", async (req, res) => {
  try {
    const user = await prisma.user.findUnique({
      where: { id: parseInt(req.params.id) },
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        createdAt: true,
      },
    });

    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }

    res.json(user);
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
});

// POST /api/users - Create new user
router.post("/", validateUser, async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { email, password, firstName, lastName } = req.body;

    // Check if user exists
    const existingUser = await prisma.user.findUnique({
      where: { email },
    });

    if (existingUser) {
      return res.status(409).json({ error: "User already exists" });
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 10);

    const user = await prisma.user.create({
      data: {
        email,
        password: hashedPassword,
        firstName,
        lastName,
      },
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        createdAt: true,
      },
    });

    res.status(201).json(user);
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
});

// PUT /api/users/:id - Update user
router.put("/:id", validateUser, async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { email, password, firstName, lastName } = req.body;
    const updateData = { email, firstName, lastName };

    if (password) {
      updateData.password = await bcrypt.hash(password, 10);
    }

    const user = await prisma.user.update({
      where: { id: parseInt(req.params.id) },
      data: updateData,
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        createdAt: true,
      },
    });

    res.json(user);
  } catch (error) {
    if (error.code === "P2025") {
      return res.status(404).json({ error: "User not found" });
    }
    res.status(500).json({ error: "Internal server error" });
  }
});

// DELETE /api/users/:id - Delete user
router.delete("/:id", async (req, res) => {
  try {
    await prisma.user.delete({
      where: { id: parseInt(req.params.id) },
    });

    res.status(204).send();
  } catch (error) {
    if (error.code === "P2025") {
      return res.status(404).json({ error: "User not found" });
    }
    res.status(500).json({ error: "Internal server error" });
  }
});

module.exports = router;

Kompatibilita a platformy

Podporované AI modely

  • GPT-4 - Najlepšie pre komplexné backend logiky
  • Claude 3 - Vynikajúce pre security best practices
  • Gemini Pro - Dobré pre rapid prototyping

Odporúčané platformy

  • ChatGPT Plus - Pre GPT-4 prístup a code generation
  • Cursor - Pre IDE integráciu a refactoring
  • GitHub Copilot - Pre inline code suggestions

Metriky úspešnosti

Kvantitatívne metriky

  • Code completeness - >95% funkcionalít implementovaných
  • Security compliance - 100% best practices adherence
  • Error handling coverage - >90% error cases handled
  • Documentation completeness - >80% endpoints documented

Kvalitatívne indikátory

  • Code readability a maintainability
  • API design consistency
  • Error message clarity
  • Security implementation quality

Tipy a triky

Pro tipy

  • Vždy špecifikujte validation library - lepšie input handling
  • Používajte environment variables pre sensitive data
  • Implementujte proper logging pre debugging
  • Testujte edge cases a error scenarios

Pokročilé techniky

  • Database transaction management
  • Caching strategies pre performance
  • Rate limiting implementation
  • API versioning considerations

Bežné problémy a riešenia

Problémy s výstupom

  • Chýbajúce error handling - pridajte comprehensive try-catch bloky
  • Slabá validácia - špecifikujte validation rules detailnejšie
  • Security gaps - zdôraznite authentication a authorization

Problémy s kontextom

  • Nesprávny database syntax - špecifikujte presnú verziu a ORM
  • Chýbajúce imports - pridajte required dependencies
  • Zlé error responses - definujte consistent error format

Budúci vývoj

Plánované vylepšenia

  • GraphQL endpoint generovanie
  • Microservices template creation
  • API gateway integration
  • Real-time WebSocket endpoints

Experimentálne varianty

  • AI-powered API testing generation
  • Automatic performance optimization
  • Database migration script generation
  • API client SDK generation

Podobné prompty

Programovanie

Ďalší prompt v kategórii

Preskúmajte ďalšie prompty v rovnakej kategórii.

Zobraziť viac →
Odporúčané

Najlepšie prompty

Objavte najpopulárnejšie a najúčinnejšie prompty.

Preskúmať všetky →