Transformações de solicitações e respostas
Personalize as cargas de solicitações e respostas do API Gateway usando modelos de mapeamento (VTL) para integrá-lo a diversos sistemas de back-end.
Transformações de solicitações e respostas é uma aula grátis de Serverless Backend with AWS Lambda & API Gateway no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Serverless Backend with AWS Lambda & API Gateway, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Serverless Backend with AWS Lambda & API Gateway inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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')"
}
#endVTL 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
$!variableto 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.
Perguntas Frequentes
A aula “Transformações de solicitações e respostas” é grátis?
Sim — o texto completo de “Transformações de solicitações e respostas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Serverless Backend with AWS Lambda & API Gateway, atualize para CoddyKit PRO. O curso de Serverless Backend with AWS Lambda & API Gateway inclui 4 aulas no total.
O que vou aprender em “Transformações de solicitações e respostas”?
Personalize as cargas de solicitações e respostas do API Gateway usando modelos de mapeamento (VTL) para integrá-lo a diversos sistemas de back-end. Você pratica Serverless Backend with AWS Lambda & API Gateway com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Serverless Backend with AWS Lambda & API Gateway?
Nenhuma experiência prévia é necessária. Serverless Backend with AWS Lambda & API Gateway no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Transformações de solicitações e respostas”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Serverless Backend with AWS Lambda & API Gateway?
Sim. Cada aula de Serverless Backend with AWS Lambda & API Gateway inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Armazenamento em cache e limitação de tráfego
- Transformações de solicitações e respostas
- Nomes de domínio personalizados e otimização de borda
- APIs WebSocket para comunicação em tempo real