Construindo APIs com Amazon API Gateway e AWS Lambda

Download Construindo APIs com Amazon API Gateway e AWS Lambda

Post on 20-Jan-2017

467 views

Category:

Technology

0 download

Embed Size (px)

TRANSCRIPT

<p>PowerPoint Presentation</p> <p>Thiago Paulino, Arquiteto de Solues2016Construindo APIs com Amazon API Gateway e AWS Lambda</p> <p> 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.</p> <p>O que esperar dessa sesso?Introduo AWS LambdaBenefciosComo funciona?Arquitetura de RefernciaDemoIntroduo AWS API-GatewayBenefciosComo funciona?Arquitetura de RefernciaDemo</p> <p>2</p> <p>Aplicao rodando na AWS</p> <p>Aplicao rodando na AWS sem auto-scaling</p> <p>AWS LambdaUm servio de processamento o qual voc no tem que pensar em:ServidoresAlta ou baixa capacidade de recursosDeploy de aplicaesEscalabilidade e tolerancia a falhasSistema operacional e atualizaesMetricas e log</p> <p>AWS LambdaAgora tudo pode ser mais fcil.Porte seu cdigo para a AWS com bibliotecas nativasExecute cdigo em parareloCrie backends, execuo baseada em eventos e processamento de dados Nunca pague por algo parado! </p> <p>Aplicao rodando na AWS com Lambda</p> <p>AWS Lambda</p> <p>8</p> <p>AWS LambdaServerless, event-driven compute servicemicroservice sem servidores</p> <p>9</p> <p>O que serverless AWS? Serverless = No pense em servidores Lambda: Recursos computacionais baseado em eventos API Gateway: Contrua APIs rest com lambda Serverless AWS = Lambda + API Gateway Lambda tem pontencial para ser o ponto focal da nuvem AWS Janakiram MSV (janakiram.com)</p> <p>Benefcios</p> <p>EVENT-DRIVEN SCALESERVERLESSSUBSECOND BILLING</p> <p>1 - AWS Lambda automatically runs your code without requiring you to provision or manage servers. Just write the code and upload it to Lambda.2 - AWS Lambda automatically scales your application by running code in response to each trigger. Your code runs in parallel and processes each trigger individually, scaling precisely with the size of the workload.3 - With AWS Lambda, you are charged for every 100ms your code executes and the number of times your code is triggered. You don't pay anything when your code isn't running.</p> <p>11</p> <p>Por que serverless AWS? Isso barato</p> <p>Como Funciona</p> <p>1. Upload do cdigo2. Configure evento e permisses3. Lambda executa em resposta a eventos4. Pague somente quando a fuo for executada</p> <p>IntegraesLambda Backend</p> <p>SNS</p> <p>CognitoKinesisDynamoS3SDKMobile, Alexa </p> <p>API Gateway</p> <p>SES</p> <p>CloudWatch</p> <p>CloudFormation</p> <p>AWS Config</p> <p>Scheduled events</p> <p>verify data formats, audit out-of-range values, filter and copy data to other tables- Add in API Gateway here as that is a huge use case. You may want to ensure you have the complete list of integrated services.- You may want to talk a bit about the push versus pull model of invocation, as well as the request response14</p> <p>Pontos de AtenoControle de PermissoStatelessLogging e Monitoramento</p> <p>Casos de Uso - Tumbnail</p> <p>verify data formats, audit out-of-range values, filter and copy data to other tables- Add in API Gateway here as that is a huge use case. You may want to ensure you have the complete list of integrated services.- You may want to talk a bit about the push versus pull model of invocation, as well as the request response16</p> <p>Procesamento de arquivos em tempo realThe Seattle Times utiliza AWS Lambda para redimensionar as imagens do seu site para diferentes dispositivos como: Computadores(Desktop e notebooks), tablets e smartphones</p> <p>Casos de Uso - ETL</p> <p>verify data formats, audit out-of-range values, filter and copy data to other tables- Add in API Gateway here as that is a huge use case. You may want to ensure you have the complete list of integrated services.- You may want to talk a bit about the push versus pull model of invocation, as well as the request response18</p> <p>Encoding de arquivosOs estudios de gravao enviam os arquivos para o Amazon S3. Aps o envio uma funo Lambda executada para iniciar o processo de agregao desses arquivos, validao, identificao e publicao.</p> <p>Casos de Uso Segurana</p> <p>verify data formats, audit out-of-range values, filter and copy data to other tables- Add in API Gateway here as that is a huge use case. You may want to ensure you have the complete list of integrated services.- You may want to talk a bit about the push versus pull model of invocation, as well as the request response20</p> <p>AWS LambdaDemo</p> <p>21</p> <p>LimitesResource LimitsDurao mxima: 5 minutosHeap mxima: 1.5 GBArmazenamento temporrio ("/tmp"): 512 MBNmero mximo de processos/threads : 1.024Tamanho mximo do pacote da aplicao (zip/jar): 50 MB</p> <p>Estendendo AWS Lambda</p> <p>Use o /tmp como cacheRode qualquer executvel (independente de linguagem)Use plugins do Grunt e Jenkins para deploysSlack + LambdaJAWS: The Server-less Application Framework</p> <p>Amazon API Gateway</p> <p>24</p> <p>Proliferao de APIsO nmero de APIs publicadas est crescendo rapidamente* Dados do ProgrammableWeb</p> <p>25</p> <p>Na AWS, ns rodamos muitas APIs</p> <p>Com o passar do tempo, ns aprendemos algumas lies</p> <p>26</p> <p>Seu feedback</p> <p>Gerenciar mltiplas verses e estgios de uma API difcil.</p> <p>27</p> <p>Seu feedback</p> <p>Gerenciar mltiplas verses e estgios de uma API difcil.Monitorar acessos de desenvolvedores terceiros consome tempo.</p> <p>28</p> <p>Seu feedback</p> <p>Gerenciar mltiplas verses e estgios de uma API difcil.Monitorar acessos de desenvolvedores terceiros consome tempo.Autorizar acessos desafiador.</p> <p>29</p> <p>Seu feedback</p> <p>Gerenciar mltiplas verses e estgios de uma API difcil.Monitorar acessos de desenvolvedores terceiros consome tempo.Autorizar acessos desafiador.Picos de trfego geram um peso operacional.</p> <p>30</p> <p>Seu feedback</p> <p>Gerenciar mltiplas verses e estgios de uma API difcil.Monitorar acessos de desenvolvedores terceiros consome tempo.Autorizar acessos desafiador.Picos de trfego geram um peso operacional.E se eu no quiser nenhum servidor?</p> <p>31</p> <p>Amazon API Gateway</p> <p>Hospede mltiplas verses e ambientes das suas APIsCrie e distribua chaves de API para desenvolvedoresBeneficie-se da Sigv4/JTW/OAuth para autorizar acesso s APIsControle e monitore requisies para proteger o backend, Cache ..Use AWS Lambda!</p> <p>32</p> <p>Fluxo de uma chamada API</p> <p>Internet</p> <p>Mobile apps</p> <p>Websites</p> <p>Servios</p> <p>API Gateway</p> <p>Funes AWS Lambda</p> <p>AWS</p> <p>API Gateway cache</p> <p>Endpoints na Amazon</p> <p>Qualquer outro endpoint acessvel</p> <p>Amazon CloudWatch</p> <p>33</p> <p>Configurao da APIVoc pode criar APIs</p> <p>Definir recursos da API</p> <p>Definir mtodos para o recursoMtodos so recurso + HTTP verb</p> <p>Lets look in details at the hierarchical structure of an API</p> <p>The top level element is the API itself, we call it a REST API.A rest API can contain many resources, resources are typed objects that are part of your APIs domain. They also represent the path through which the objects will be accessibleYou can nest resources, in our example the /pet/{petId} represents an individual pet and is a nested resource of the /pets/ resource.Each resource can declare methods. Methods are the combination of a resource + an HTTP Verb. We support 7 standard HTTP Verbs, For example, a method is the POST to the /pets/{petId} resources this would be used to create a new pet</p> <p>34</p> <p>Deploy da APIConfigurao da API pode ser implantado em um ambiente (stage)Stages so ambientes diferentes; por exemplo:Dev (e.g., example.com/dev)Beta (e.g., example.com/beta)Prod (e.g., example.com/prod)</p> <p>Now that we have declared an API with its resources and methods, we can deploy it to make it accessible to 3rd party developersAPIs are deployed to a StageStages represent environments, for example development of productionIn API Gateway Stages are like tags, and developers can create as many stages as they want. A stage is just an alphanumeric stringStages are part of the path that will be used to reach sources and methods, for example the prod stage will be available at execute-api.apigateway.com/stage/resource</p> <p>35</p> <p>Gerencie mltiplos ambientes e verses de sua APIAPI 1 (v1)Stage (dev)Stage (prod)API 2 (v2)Stage (dev)</p> <p>This is a visual representation of how versions and stages are managed by the API Gateway, and how customers can leverage these features for their APIsThe first thing well do is declared a V1 API and start configuring its resources and methodsThe next step is to deploy the API to a development stage, well keep deploying to development as we evolve our APIAt a certain point, when we are ready for 3rd party developers to access this API, we will publish it to a production stage and distribute API Keys and generated SDKsAll along we will keep deploying APIs to both dev and prod including new features and bug fixedEventually well want to make some breaking changes, and work on a much improved v2 API. However, we cannot make breaking changes to the API in production because we have thousands of developers using it.To manage this situation well simply clone the current state of the v1 API into a new API called v2, and begin development of the new versionBy cloning we can keep publishing bug fixes to the first release and supporting users that are calling it with a gentle, gradual deprecation</p> <p> developers feel like they can deliver what they want, when they want to and that makes for an extremely valuable tool </p> <p>36</p> <p>Custom domain namesVoc pode configurar custom domain namesFornea API Gateway com um certificado HTTPSCustom domain names podem ser apontados para um estgio da APIAponte para uma API e ambiente (stage)Beta (e.g., yourapi.com/beta)Prod (e.g., yourapi.com/prod)</p> <p>Customers can configure the API Gateway to use a custom domain name they provide instead of the standard AWS domain.We expect customers to bring their own signed certificate for the HTTPS endpointsDomain names can be configured to point to an API, our top level item, or directly to a specific stage within an API.Pointing a custom domain name to an API requires the stage to be included in the pathIf the domain name is pointed directly at a stage there is no need for the path variable, resources can be accessed directly form the API root /</p> <p>37</p> <p>Segurana Sigv4</p> <p>Call login API, no authentication requiredClienteAPI GatewayBackend/login</p> <p>AWS Lambda fn_login</p> <p>User accounts database</p> <p>Credentials verified</p> <p>Amazon Cognito developer authenticated identities</p> <p>Access and secret key/login</p> <p>Receives credentials to sign API calls</p> <p>API Gateway uses throttling to help protect customer backends and send only request that they can handleTo implement throttling we use the token bucket algorithmCustomers can set the number of RPS calls they know their backend can handle, and a rate at which the bucket is refilled</p> <p>38</p> <p>Segurana Custom Authorizer</p> <p>API Gateway uses throttling to help protect customer backends and send only request that they can handleTo implement throttling we use the token bucket algorithmCustomers can set the number of RPS calls they know their backend can handle, and a rate at which the bucket is refilled</p> <p>39</p> <p>Caching API responses</p> <p>Lets put the two together and look at the execution path of an API callFirst, when we receive a request, we will check the dedicated cache (if its been configured)If we have an item in the cache then we can handle the request regardless of the throttling configuration, it will have no effect on our customers backendNext, if we dont have a cache, we check the throttling configuration and the current throttling state (our bucket)If we are above the limit we will return a 429 responseOtherwise we will execute the backend call and return the resultAs we mentioned our generated SDKs automatically know how to handle throttling responses, and they will perform an exponential backoff while retrying the call40</p> <p>Caching API responsesVoc pode configurar a chave de cache e TTL da resposta da APIItens cacheados retornam sem chamar o backendUm cache dedicado para voc, por estgio (stage)0.5 GB a 237 GB de cache</p> <p>To limit the number of requests their backend can receive, and further bring down latency customers can configure a dedicated cache for each stage of their APIFor each method in their APIs customers can configure which parameters between path, query string and headers form the item key in the cache, and assign each item a time to liveAPI Gateway automatically caches responses where configured and avoids calling the customers backend if the cached item is available and validCustomers have access to APIs to manage their cache in the API GatewayWhen a stage is configured with a dedicated cache, and an item is found to be in cache and valid for a request that would otherwise be throttled, the API Gateway will handle the request and return the cached responseCustomers can pick for a range of possible cache sizes to provision a dedicated cache from their stage, from 0.5GB all the way up to 237GB</p> <p>41</p> <p>API GatewayBack end GET - /sayHello</p> <p>AWS Lambda fn_sayHello/sayHello{ message : hello world}</p> <p> Hello world </p> <p>#set($root = $input.path('$'))</p> <p> $root.message </p> <p>Input/output transforms</p> <p>Example of a simple transformation flow</p> <p>API Gateway + Lambda = Server-less backendUse AWS Lambda to run business logicUse API Gateway to expose the AWS Lambda functions as endpointsTransforms Lambdas JSON output to XML for their APIs</p> <p>42</p> <p>Input/output transforms</p> <p>Filtrar resultados de outputRemover dados privados ou desnecessriosFiltrar o tamanho do dataset para melhorar a performance da APIGET para POSTLeia os query string parameters de sua requisio GET e crie um corpo para fazer requisies POST para seu back endJSON para XMLReceba um input JSON e transforme-o em XML para seu back endReceba um JSON de uma funo AWS Lambda e transforme-o para XML</p> <p>Lets look at how request and response data can be transformed in-flight.We use Apache Velocity as the standard to create, save and execute templatesWe have been working with our customers on this and during development we have seen the following use-cases from themFilter API responses. In many cases legacy APIs tended to return verbose responses with too many objects. Large payloads are a struggle for mobile applications, so customers are using the templates to traverse the response schema and filter the output to return only the necessary fieldsRPC to REST. Customers have RPC-style APIs that they wanted to expose to the world in the form of RESTful APIs. RPC often only accept POST calls. Customers used the transform templates to accept a GET call in the API Gateway, then generate the POST body for their backend call reading parameters from the path, query string and headersCustomers who want to leverage Lambda but only run XML APIs have been using the transform templates to receive the JSON output from Lambda, and turn it into an XML before sending it back to the end user. This has allowed them to completely switch their backend technology while causing no disruption for 3rd party developers utilizing their APIs, very neat tablecloth trick. Example: Twilio</p> <p>43</p> <p>Outras FuncionalidadesMock IntegrationImportador de SwaggerGere SDKs a partir de suas APIsCustom Domain / HTTPSClient-Side SSL AuthenticationLink lambda version</p> <p>API Gateway can generate client SDKs based on a customers API definition.Simply select the...</p>

Recommended

View more >