> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devinenterprise.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Implementare l'API Bookings a partire dalla specifica OpenAPI

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero
  title="Implementare l'API delle prenotazioni a partire dalla specifica OpenAPI"
  description="Passa a Devin una specifica YAML e ottieni handler di route Express completamente implementati, modelli Prisma, validazione Zod e test di integrazione Supertest — in linea con i pattern esistenti della tua codebase."
  prompt="Implementa i seguenti endpoint dell'API delle prenotazioni utilizzando il nostro stack esistente Express + Prisma. Segui i pattern in src/api/v2/users/ per la struttura delle route, la gestione degli errori e il middleware. Ricava gli schemi Zod dagli schemi della specifica riportati di seguito.

Endpoints:
- GET /api/v2/bookings (elenco con paginazione: parametri di query: page, startDate, endDate)
- POST /api/v2/bookings (creazione — 201 in caso di successo, 409 in caso di conflitto di fascia oraria)
- GET /api/v2/bookings/:id
- PATCH /api/v2/bookings/:id (aggiornamento parziale)
- DELETE /api/v2/bookings/:id (soft delete)
- POST /api/v2/bookings/:id/confirm (200 in caso di successo, 422 se già annullata)
- POST /api/v2/bookings/:id/cancel

Schema CreateBookingInput (obbligatori: title, startTime, endTime, roomId):
- title: string, maxLength 200
- startTime: string, date-time
- endTime: string, date-time
- roomId: string, uuid
- notes: string, maxLength 1000, opzionale

Scrivi test di integrazione con Supertest per ogni endpoint — copri casi di successo, errori di validazione, errori di autenticazione e casi limite come fasce orarie sovrapposte. Esegui tutti i test e verifica che ogni endpoint funzioni. Se qualcosa fallisce, esegui il debug e correggi il problema — continua a iterare finché tutti i test non passano. Non aprire una PR finché non funziona tutto end-to-end."
  category="Sviluppo funzionalità"
  features=""
/>

<div className="uc-detail-wrapper">
  <Tip>Non vuoi configurare tutto manualmente? Incolla un collegamento a questa pagina in una sessione di Devin e chiedigli di configurare tutto per te.</Tip>

  <Steps>
    <Step title="(Facoltativo) Analizza i pattern API esistenti">
      Se non sei sicuro di come sia strutturata la tua API Express o a quali pattern fare riferimento, utilizza [Ask Devin](https://app.devin.ai/search?utm_source=docs\&utm_medium=use-case-gallery) per analizzarla prima:

      <PromptBlock agent="ada">
        ```txt Research our Express API patterns theme={null}
        Mostrami com'è strutturata la nostra API Express:
        1. Qual è la struttura delle cartelle sotto src/api/v2/?
        2. In che modo interagiscono route handler, controller e servizi?
        3. Quale middleware usiamo per l'autenticazione e la validazione?
        4. Come sono formattate le risposte di errore?
        5. Com'è configurato il nostro setup di test (Supertest, configurazione del DB di test)?
        ```
      </PromptBlock>

      Puoi anche usare [DeepWiki](https://deepwiki.com) per esplorare API open source con pattern simili — ad esempio, cerca esempi Express + Prisma + Zod per vedere come altri progetti strutturano i loro route handler e la validazione.

      Puoi avviare una sessione di Devin direttamente da Ask Devin, e manterrà tutto ciò che ha appreso come contesto.
    </Step>

    <Step title="Collega Devin alla tua specifica OpenAPI">
      Inizia indicando a Devin dove si trova la specifica e quale risorsa implementare. Devin legge ogni path, schema e definizione di errore nel file YAML, quindi confronta automaticamente le tue route Express esistenti per rispettare le convenzioni.

      Ecco un estratto del tipo di specifica con cui lavora Devin — una definizione OpenAPI 3.0 standard per una risorsa di prenotazioni:

      ```yaml theme={null}
      # openapi/bookings-v2.yaml (excerpt)
      openapi: "3.0.3"
      info:
        title: Bookings API
        version: "2.0.0"
      paths:
        /api/v2/bookings:
          get:
            summary: List bookings
            parameters:
              - name: page
                in: query
                schema: { type: integer, default: 1 }
              - name: startDate
                in: query
                schema: { type: string, format: date }
              - name: endDate
                in: query
                schema: { type: string, format: date }
            responses:
              "200":
                description: Paginated list of bookings
                content:
                  application/json:
                    schema:
                      $ref: "#/components/schemas/BookingListResponse"
          post:
            summary: Create a booking
            requestBody:
              required: true
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/CreateBookingInput"
            responses:
              "201":
                description: Booking created
              "409":
                description: Time slot conflict
        /api/v2/bookings/{id}/confirm:
          post:
            summary: Confirm a booking
            responses:
              "200":
                description: Booking confirmed
              "422":
                description: Booking already cancelled
      components:
        schemas:
          CreateBookingInput:
            type: object
            required: [title, startTime, endTime, roomId]
            properties:
              title:
                type: string
                maxLength: 200
              startTime:
                type: string
                format: date-time
              endTime:
                type: string
                format: date-time
              roomId:
                type: string
                format: uuid
      ```

      <PromptBlock>
        ```txt Implementa l'API delle prenotazioni a partire dalla specifica OpenAPI theme={null}
        Implementa gli endpoint definiti in openapi/bookings-v2.yaml per
        /api/v2/bookings. La specifica definisce:

        - GET /api/v2/bookings (elenco con paginazione + filtro per intervallo di date)
        - POST /api/v2/bookings (creazione)
        - GET /api/v2/bookings/:id
        - PATCH /api/v2/bookings/:id (aggiornamento parziale)
        - DELETE /api/v2/bookings/:id (eliminazione logica)
        - POST /api/v2/bookings/:id/confirm
        - POST /api/v2/bookings/:id/cancel

        Usa il nostro stack esistente Express + Prisma. Segui le convenzioni in
        src/api/v2/users/ per la struttura delle route, la gestione degli errori e il middleware.
        Deriva gli schemi Zod dalle definizioni di richiesta/risposta OpenAPI.

        ## Testing & verification
        - Write integration tests with Supertest for every endpoint
        - Cover success cases, validation errors, auth failures, and
          business logic edge cases (e.g., overlapping time slots)
        - Run all tests and verify every endpoint works correctly
        - If anything fails — test failures, runtime errors, missing
          middleware — debug and fix it. Keep iterating until all tests pass.
        - Do not open a PR until everything works end-to-end
        ```
      </PromptBlock>

      If your spec isn't checked into the repo yet, paste it directly into the session or attach the YAML/JSON file when starting.
    </Step>

    <Step title="Devin matches your Express patterns">
      The single most impactful thing you can do is reference a well-implemented resource in your codebase. Devin studies that code and replicates the folder structure, naming conventions, middleware chain, and error handling — so the new endpoints look like they were written by the same developer.

      For example, Devin reads `src/api/v2/users/router.ts` and produces a matching bookings router:

      ```typescript theme={null}
      // src/api/v2/bookings/router.ts  (generated by Devin)
      import { Router } from "express";
      import { authenticate } from "@/middleware/auth";
      import { validate } from "@/middleware/validate";
      import { BookingsController } from "./controller";
      import {
        createBookingSchema,
        updateBookingSchema,
        listBookingsQuerySchema,
      } from "./schemas";

      const router = Router();
      const ctrl = new BookingsController();

      router.use(authenticate);

      router.get("/", validate({ query: listBookingsQuerySchema }), ctrl.list);
      router.post("/", validate({ body: createBookingSchema }), ctrl.create);
      router.get("/:id", ctrl.getById);
      router.patch("/:id", validate({ body: updateBookingSchema }), ctrl.update);
      router.delete("/:id", ctrl.softDelete);
      router.post("/:id/confirm", ctrl.confirm);
      router.post("/:id/cancel", ctrl.cancel);

      export default router;
      ```

      Devin also derives Zod schemas directly from the OpenAPI component definitions, so request validation stays in sync with the spec:

      ```typescript theme={null}
      // src/api/v2/bookings/schemas.ts  (generato da Devin)
      import { z } from "zod";

      export const createBookingSchema = z.object({
        title: z.string().max(200),
        startTime: z.string().datetime(),
        endTime: z.string().datetime(),
        roomId: z.string().uuid(),
        notes: z.string().max(1000).optional(),
      });

      export const updateBookingSchema = createBookingSchema.partial();

      export const listBookingsQuerySchema = z.object({
        page: z.coerce.number().int().positive().default(1),
        limit: z.coerce.number().int().min(1).max(100).default(20),
        startDate: z.string().date().optional(),
        endDate: z.string().date().optional(),
      });
      ```

      Assicurati che la [configurazione dell'ambiente](/it/onboard-devin/environment) includa la configurazione del database di test e tutte le variabili d'ambiente necessarie affinché Devin possa eseguire l'intera suite di test in locale. Se la tua API richiede credenziali (URL del database, segreto JWT, ecc.), aggiungile come [Secrets](/it/product-guides/secrets) prima di avviare la sessione — oppure forniscile durante la sessione tramite chat.
    </Step>

    <Step title="Devin consegna una PR testata">
      Devin legge la specifica, analizza il codice esistente e implementa ogni endpoint in modo che rispetti sia il contratto OpenAPI sia le convenzioni della tua codebase Express. Ecco com'è fatta una PR tipica:

      ```
      feat: Implement /api/v2/bookings endpoints from OpenAPI spec

      src/api/v2/bookings/
        router.ts              (Express route definitions + middleware)
        controller.ts          (request handling)
        service.ts             (business logic)
        repository.ts          (Prisma queries)
        schemas.ts             (Zod validation from spec)
      prisma/migrations/
        20260219_add_bookings/  (migration)
      src/__tests__/
        bookings.integration.ts (Supertest tests)
      ```

      Devin esegue la suite di test Supertest prima di aprire la PR:

      ```
        /api/v2/bookings
          GET /
            passes returns paginated bookings (42ms)
            passes filters by date range (38ms)
            passes returns 401 without auth (8ms)
          POST /
            passes creates booking with valid data (61ms)
            passes returns 400 for missing required fields (12ms)
            passes returns 409 for overlapping time slot (29ms)
          PATCH /:id
            passes updates booking fields (22ms)
            passes returns 404 for non-existent booking (9ms)
          POST /:id/confirm
            passes transitions status to confirmed (18ms)
            passes returns 422 for already-cancelled booking (11ms)

        16 passing (412ms)
      ```
    </Step>

    <Step title="Approfondisci ciò che la specifica non copre">
      La specifica OpenAPI definisce il contratto ma raramente include le regole di business, la logica di autorizzazione o i requisiti di performance. Usa prompt di follow-up per colmare le lacune:

      <PromptBlock>
        ```txt Add authorization rules theme={null}
        Solo il creatore della prenotazione o un admin devono poter eseguire PATCH o DELETE
        su una prenotazione. Gli endpoint di conferma e annullamento devono anche richiedere il ruolo
        organizer. Usa il nostro middleware esistente per il controllo dei ruoli da
        src/middleware/authorize.ts.
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt Add rate limiting and caching theme={null}
        Aggiungi rate limiting a POST /api/v2/bookings (20 al minuto per utente).
        Memorizza in cache le risposte di GET /api/v2/bookings in Redis con un TTL di 30 secondi,
        che va invalidato in caso di qualsiasi operazione di scrittura.
        ```
      </PromptBlock>
    </Step>

    <Step title="Rivedi la PR con Devin Review">
      Quando Devin apre la PR, usa [Devin Review](https://app.devin.ai/review?utm_source=docs\&utm_medium=use-case-gallery) per rivedere l'implementazione. Devin Review può individuare problemi come mancata gestione degli errori, formati di risposta incoerenti o endpoint che non corrispondono alla specifica.

      Se Devin Review segnala dei problemi, puoi usare **Autofix** per fare in modo che Devin li corregga automaticamente: apre una sessione di follow-up, applica le correzioni e invia un commit aggiornato senza che tu debba descrivere manualmente ogni modifica.
    </Step>
  </Steps>
</div>
