0Pricing
Serverless Backend with AWS Lambda & API Gateway · Lección

Transformaciones de solicitudes y respuestas

Personalice las cargas útiles de solicitudes y respuestas de API Gateway mediante plantillas de mapeo (VTL) para integrarse con diversos sistemas backend.

Transformaciones de solicitudes y respuestas es una lección gratuita de Serverless Backend with AWS Lambda & API Gateway en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Serverless Backend with AWS Lambda & API Gateway, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Bridging the Data Gap

Imagine your API clients speak one data language, but your backend service understands another. How do you make them communicate smoothly?

API Gateway's request and response transformations act as a universal translator, modifying payloads to ensure compatibility between different systems.

Introducing Mapping Templates

At the heart of transformations are mapping templates. These are text-based templates written using the Velocity Template Language (VTL).

You define a VTL template that tells API Gateway exactly how to restructure or modify the incoming (request) or outgoing (response) data.

Request Transformations

Request transformations modify the data sent by your client before it reaches your backend service (like a Lambda function).

This is useful for:

  • Simplifying complex client requests for a backend.
  • Adding specific headers or parameters.
  • Converting data formats (e.g., XML to JSON, or a different JSON structure).

VTL for Request Mapping

Here's a simple VTL example for a request. It takes a client's id and qty and maps them to productId and quantity for your backend.

The $input variable gives you access to the incoming request body and parameters.

#set($body = $input.json('$'))
{
  "productId": "$body.id",
  "quantity": $body.qty
}

Accessing Request Context

Besides the body, you can access other request details like path parameters, query strings, and headers using the $context variable.

This allows you to enrich your backend's input with valuable contextual information from the API call.

#set($body = $input.json('$'))
{
  "userId": "$context.authorizer.claims.sub",
  "resourcePath": "$context.resourcePath",
  "itemId": "$input.params('itemId')",
  "requestedQuantity": $body.qty
}

Response Transformations

Response transformations modify the data returned by your backend service before it's sent back to the client.

This is crucial for:

  • Standardizing API responses across different backends.
  • Masking sensitive internal details from clients.
  • Converting backend output to a client-friendly format.

VTL for Response Mapping

Similar to requests, you use VTL to transform responses. Here, a backend's result field is mapped to a more generic data field for the client.

The $input variable in a response template refers to the backend's output.

#set($body = $input.json('$'))
{
  "status": "success",
  "data": $body.result
}

Conditional Response Mapping

API Gateway allows you to define different response templates based on the backend's HTTP status code. This means you can have a specific template for success (e.g., 200 OK) and another for errors (e.g., 400 Bad Request).

This provides granular control over how different outcomes are presented to the client.

#if($input.path('$.statusCode') == 200)
{
  "message": "Operation successful."
}
#else
{
  "error": "$input.path('$.errorMessage')"
}
#end

VTL Best Practices

When writing VTL templates:

  • Keep it simple: Avoid complex logic; delegate to your backend if needed.
  • Test thoroughly: Use API Gateway's test invocation feature.
  • Use $util.urlEncode: Encode values when placing them into URLs or query strings.
  • Handle nulls: Use $!variable to output an empty string if a variable is null.

Quick Check

You've learned how API Gateway transformations can reshape data. Which of the following are key benefits of using request/response transformations?

Recap: Mastering Transformations

You've learned how API Gateway transformations, powered by VTL mapping templates, are essential for building flexible and robust APIs.

By shaping both incoming requests and outgoing responses, you can ensure seamless communication between diverse clients and backend services, improving maintainability and reducing complexity.

Preguntas frecuentes

¿La lección «Transformaciones de solicitudes y respuestas» es gratis?

Sí — el texto completo de «Transformaciones de solicitudes y respuestas» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Serverless Backend with AWS Lambda & API Gateway, actualiza a CoddyKit PRO. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.

¿Qué aprenderé en «Transformaciones de solicitudes y respuestas»?

Personalice las cargas útiles de solicitudes y respuestas de API Gateway mediante plantillas de mapeo (VTL) para integrarse con diversos sistemas backend. Practicas Serverless Backend with AWS Lambda & API Gateway con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Serverless Backend with AWS Lambda & API Gateway?

No se requiere experiencia previa. Serverless Backend with AWS Lambda & API Gateway en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Transformaciones de solicitudes y respuestas»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Serverless Backend with AWS Lambda & API Gateway?

Sí. Cada lección de Serverless Backend with AWS Lambda & API Gateway incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Almacenamiento en caché y limitación de tráfico
  2. Transformaciones de solicitudes y respuestas
  3. Nombres de dominio personalizados y optimización perimetral
  4. API WebSocket para comunicación en tiempo real
← Volver a Serverless Backend with AWS Lambda & API Gateway