07. Amazon API Gateway
A service that enables creating, publishing, maintaining, monitoring, and securing APIs at scale. It is often used in conjunction with AWS Lambda to create serverless RESTful interfaces.
How Does an API Gateway Work?
An API Gateway acts as an intermediary that enables communication between different applications and services, facilitating the exchange of data over the network. It receives requests, known as "API calls", from both internal and external sources, routes these requests to the corresponding API, and then returns the responses to the user or device that made the request.
For example, imagine that a user of an application needs to access four different services to complete a process. Instead of allowing microservices to call each other directly, we make all calls through the API Gateway. This simplifies communication and improves the management of interactions between services.
Amazon API Gateway is a managed service that simplifies the management of common API-related tasks, such as:
- Routing
- Security
- Caching
- Throttling
- Monitoring
Why use an API Gateway?
At its core, an API Gateway accepts remote requests and returns responses, providing a simple and reliable experience for your customers.
Benefits of API Gateway
- Abuse Protection: API Gateway helps protect your APIs from overuse and abuse by enabling you to implement authentication, authorization, and rate limiting capabilities.
- Easy Analytics and Monitoring: With built-in functions, it simplifies the collection of analytics data and monitoring of API performance.
- Broker for Microservices: In a microservices architecture, a single request can require calls to dozens of different applications. API Gateway acts as an intermediary, facilitating communication between services.
- Centralization of Services: As you add or update API services, API Gateway ensures that your users can find everything in one place.
Disadvantages and Challenges of API Gateway
- Routing Rules Configuration: Routing rules need to be established, which can require additional effort.
- Potential Complexity: With all API rules concentrated in one place, there is a risk of increased management complexity.
- Single Point of Failure: Using an API Gateway can introduce the possibility of a single point of failure if not properly managed.
API Gateway Security
API Gateway security can be broken down into several main categories:
1. Identity and Access Management
- Access control is the primary security driver for API Gateway technology.
- It allows an organization to manage who can access an API and establish rules for how data requests are handled.
- With all traffic routed through an API Gateway, IT security experts feel more confident in monitoring the organization’s security.
2. API Call Security
- API Gateway allows all API calls to be routed through a single point, making it easier to assess, transform, and secure calls across the entire infrastructure.
- When traffic passes through the gateway, security experts have a clear view of what is happening and can more easily implement changes.
3. DDoS and Threat Protection
- Without threat protection, API Gateway and its APIs, as well as native integration server services, are vulnerable.
- This makes the system susceptible to attacks, such as DDoS or SQL injections, perpetrated by malware or anonymous attackers.
4. Input Validations
- Inadequate input validations can allow hackers to exploit vulnerabilities in the system.
- Attacks can use existing inputs to figure out what is accepted or rejected, until they find an entry point to compromise the integrity of the API.
Main Types of Input Validations:
- Message Size: Limiting the message size is essential, especially if you are certain that you will not receive large messages.
- SQL Injection: SQL injection protection prevents potentially malicious requests from being processed.
- XML Threat Protection: Malicious attacks on XML applications usually involve large and recursive payloads, XPath/XSLT or CData injections, which can overload the parser and cause the service to fail.
- Rate Limiting: Requiring authentication of all API users and logging of all API calls allows providers to limit the consumption rate of each user.
AWS API Gateway Features
A - API Management: Allows you to easily create RESTful and WebSocket APIs. You can define endpoints, HTTP methods, and model the response and request data.
B - Backend Integration: Supports integration with various AWS services such as AWS Lambda, EC2, and DynamoDB, as well as external backends such as HTTP servers.
C - Data Modeling and Validation: Provides the ability to model and validate requests and responses using JSON schemas.
D - Traffic Management: Allows you to control traffic distribution, including the implementation of throttling and usage quotas, helping to protect your services from sudden traffic spikes.
E - Authentication and Authorization: Supports multiple security options, such as authentication via AWS IAM, Amazon Cognito User Pools, and integration with external identity providers.
F - Monitoring and Logs: Integrates with Amazon CloudWatch to provide metrics and logs, allowing you to efficiently monitor and debug your APIs.
G - API Versioning: Allows you to manage different versions of your API, making it easier to transition between versions without impacting existing users.
H - CORS (CrossOrigin Resource Sharing): Makes it easy to configure CORS to allow API calls from different origins.
I - Performance and Scalability: API Gateway is a managed service that automatically scales to meet demand, without you having to manage the infrastructure.
Types of APIs that Amazon API Gateway Supports
HTTP API
- Description: Low-cost, low-latency REST API.
- Features:
- Native support for OIDC and OAuth2.
- Native CORS support.
- Usage: Ideal for building a CRUD API with AWS Lambda and DynamoDB.
WebSocket API
- Description: WebSocket API with persistent connections.
- Usage: Ideal for real-time use cases, such as chat applications or dashboards.
- Example:
- Building a serverless chat application using WebSocket API, AWS Lambda, and DynamoDB.
REST API
- Description: REST API that offers full control over requests and responses.
- Features: Includes API management capabilities.
- Usage: Create an API Gateway REST API with AWS Lambda integration.
Private REST API
- Description: REST API that can only be accessed within an AWS Virtual Private Cloud (VPC).
Backend Flexibility
Amazon API Gateway allows you to have broad flexibility in choosing backend technologies, including:
- AWS Lambda: To execute serverless functions in response to API calls.
- Amazon DynamoDB: To store and retrieve data in a NoSQL table.
- Amazon RDS: To access relational databases (such as MySQL, PostgreSQL).
- Amazon Aurora: A relational database compatible with MySQL and PostgreSQL.
- Amazon S3: To serve static content and store files.
- AWS Step Functions: To orchestrate calls to multiple AWS services in a workflow.
- Amazon SNS (Simple Notification Service): To send notifications.
- Amazon SQS (Simple Queue Service): To queue and process messages.
- AWS AppSync: To implement GraphQL APIs.
- Amazon CloudFront: To deliver content through a content delivery network (CDN). - Amazon Kinesis: For receiving and processing real-time data streams.
- AWS IAM (Identity and Access Management): For managing permissions and authentication.
- Amazon Cognito: For user authentication and identity management.
- Amazon EventBridge: For integrating events from different AWS services.
- Elastic Load Balancing (ELB): For routing traffic to EC2 instances and other services.
- Amazon EC2: For accessing virtual server instances.
- Amazon ECS (Elastic Container Service): For running containers.
- Amazon EKS (Elastic Kubernetes Service): For managing Kubernetes clusters.
- Amazon Textract: For extracting text and data from documents.
- AWS Step Functions: For building complex workflows.
AWS API Gateway Use Cases
1. Mobile and Web Applications: You can use API Gateway to build scalable backends for mobile and web applications, enabling them to communicate with cloud services.
2. Microservices: In a microservices architecture, API Gateway acts as an entry point for interactions between services, simplifying communication.
3. Serverless APIs: By combining AWS Lambda and API Gateway, you can build serverless APIs. This eliminates the need to manage servers, reducing costs and increasing efficiency.
4. Data Service Integration: Use API Gateway to expose data from services such as S3, DynamoDB, and others, enabling easy and secure queries and operations.
5. WebSockets: Build real-time applications, such as chats or real-time updates, using API Gateway's WebSocket functionality.
6. Third-Party Service Exposure: API Gateway can act as a proxy, allowing you to expose APIs from external services in a controlled and secure manner.
7. IoT Services: Ideal for connecting IoT devices to backends, allowing devices to communicate with the cloud in a secure and scalable manner.
08. AWS AppSync
Introduction to GraphQL and AWS AppSync
In the fast-paced world of web and mobile app development, efficiency and real-time capabilities are not just nice-to-haves—they’ve become must-haves.
Imagine that you’re at a restaurant and instead of placing multiple orders to get all the dishes you want, you can simply place a single order that includes everything at once.
That’s exactly what GraphQL and AWS AppSync bring to the development landscape, enabling developers to build dynamic, scalable apps with ease.
GraphQL, which was conceived by Facebook in 2012 and publicly released in 2015, is a query language for APIs and a runtime environment that lets you query your data with a type system that’s defined.
Unlike traditional REST APIs, which often require developers to load multiple URLs, GraphQL makes it possible to get all the information your application needs in a single request. This ensures a smoother and more efficient experience, even on slow mobile connections — imagine getting a large meal all at once, instead of waiting for individual dishes. On the other hand, AWS AppSync can be thought of as the “GraphQL of AWS.” It’s a managed service that further simplifies the development process by creating serverless GraphQL and Pub/Sub APIs. Think of AppSync as a conductor in an orchestra: it coordinates all the different instruments (or services) so that they play in harmony. With a single endpoint, developers can securely and efficiently query, update, or publish data, enabling them to build interactive, feature-rich applications. In short, both GraphQL and AWS AppSync not only save time and resources, but also improve the user experience by transforming the way we interact with data and build applications.
Get ready to explore these powerful tools that will take your development to the next level!
Key Features of GraphQL
1. Precisely Defined Queries
- GraphQL allows developers to specify exactly what data they want in their queries.
- It’s like placing a custom order at a sandwich shop: instead of getting a standard sandwich, you can order exactly the ingredients you want, without a single unnecessary item.
- This minimizes waste and ensures you get exactly what you need, optimizing the efficiency of your application.
2. Single Request, Many Responses
- With GraphQL, you can fetch all the data you need in a single request, unlike REST APIs, which often require multiple calls.
- Imagine you’re hosting a party, and instead of making multiple trips to the grocery store (one for drinks, one for snacks, one for dessert), you can place a single delivery order that includes everything you need for the party.
- This reduces latency and makes loading data much faster.
3. Strong Typing
- GraphQL uses a strong type system, allowing developers to define clear structures for their data.
- Think of it like a detailed map of a city: by following a well-defined map, you can easily find what you’re looking for without getting lost.
- This strong typing helps prevent errors and makes code maintenance easier, providing security for interactions with the API.
4. Evolution Without Breaking
- One of the great advantages of GraphQL is its ability to evolve without breaking backwards compatibility.
- It’s like a growing tree: as new branches are added, the tree continues to flourish, but the roots remain firmly planted.
- This means that new functionality can be added without negatively impacting clients already using a previous version of the API.
5. Real-Time Subscriptions
- GraphQL supports subscriptions, allowing applications to receive updates in real time.
- Think of it as a weather alert service – instead of constantly checking the temperature, you subscribe to receive a notification as soon as there are significant changes.
- This makes applications more dynamic and responsive, offering a richer user experience.
6. Rich Tools and Ecosystem
- The ecosystem around GraphQL is vibrant, with several tools and libraries that facilitate development.
- Think of it as a well-stocked toolbox: each tool has a specific purpose and can make your life easier in different ways.
- Whether for queries, data management or integrations, GraphQL has a wide range of features that make development more efficient and enjoyable.
7. Automatic Documentation
- Finally, with GraphQL, documentation is automatically generated from the schema.
- This is like having a personal assistant that follows your daily life and notes all your activities and appointments. - So when you need to check what you did, the information will always be accessible and organized, helping you better understand how to interact with the API.
GraphQL Operations
We have 3 different operations in GraphQL:
Query : used to retrieve data, such as a GET request.
Mutation : used to modify data, such as CREATE, UPDATE or DELETE.
Subscription : used to subscribe to data changes and receive real-time notifications.
The big question and why choose AppSync?
Choosing AWS AppSync for developing applications that use GraphQL can bring a number of significant benefits. Below, I present some reasons, accompanied by real-world cases that illustrate how companies are leveraging AppSync to achieve their goals:
1. Rapid and Simplified Development
Real-World Case Study: Fast-growing education technology startup Knowt has developed an innovative app that changes how students and teachers study and create assignments. Using a powerful algorithm and artificial intelligence, the app quickly converts notes into quizzes and flashcards. Founded in 2016 by Abheek Pandoh and Daniel Like, Knowt was born from an opportunity to improve learning through student note-taking. It started as an Android app and quickly expanded to iOS and the web.link
2. Real-Time Data Integration
Real Case Study: Sky Italia wanted to provide a better experience to sports fans by sending real-time data updates during live broadcasts of sporting events, and using AWS AppSync, they were able to optimize data transfers during peak traffic times and deliver sports updates to viewers in milliseconds. link
3. Automatic Scalability
Real Case Study: To provide an engaging, low-latency streaming experience, Amazon Music decided to build a centralized, cloud-based queuing system. This system also features on-device storage, enabling offline playback and automatic data synchronization between clients and the central system, which is critical to handling the heavy usage of millions of users switching between devices and network connectivity.link
4. Simplified API Management
Real Case Study: Automatic Data Processing (ADP) was looking to modernize its flagship solutions, MyADP and ADP Mobile, to provide a seamless experience for its 17+ million users. As a global technology company specializing in human capital management (HCM) and payroll services, ADP is committed to building innovative products. To achieve this, low latency and a high-quality user experience are key. link
5. Improved User Experience
Real Case Study: ResMed, a leader in digital health, is a leading global provider of cloud-connected solutions for people with sleep apnea, COPD, asthma, and other chronic conditions. As of 2021, the company has already impacted the lives of more than 133 million people in over 140 countries and now aims to improve 250 million lives by 2025. To achieve this ambitious goal, ResMed needs an agile, serverless solution that will drive user satisfaction and meet growing demand.
To meet this need, ResMed turned to Amazon Web Services (AWS) ** solutions to scale its support to more users globally, reduce application latency, and quickly implement new features. When developing its myAir app, the company chose AWS AppSync, a serverless GraphQL and Pub/Sub API service that makes it easy to build modern web and mobile applications. Combined with other AWS solutions, AppSync will enable ResMed to reduce operational overhead, improve the user experience, and provide more accurate and valuable insights through machine learning. This focus on improving the user experience not only increases satisfaction, but also enhances ResMed’s ability to fulfill its mission of positively **impacting the lives of millions of people. link
7. Easy Maintenance and Evolution
Real Case Study: The article "Adding Real-Time Interactivity to Your Live Streams with AWS AppSync" explores how to implement interactivity in live broadcasts using AWS AppSync. It describes the importance of engaging viewers through features such as live chat, polls, and reactions during events. The author presents a practical example of an application that integrates AppSync with a React front-end, enabling real-time communication with AWS streams. In addition, the article details the configuration of GraphQL subscriptions to facilitate instant interaction, improving the user experience and increasing engagement during broadcasts.
link
8. Enhanced Security
In the current context, where information security is a key priority for companies across all sectors, AWS AppSync stands out as a robust solution that enhances application security.
The companies mentioned in our examples demonstrate how implementing AppSync not only improves efficiency and user experience, but also strengthens data protection. AppSync makes it easy to implement high-level authentication and authorization, ensuring that sensitive information is only accessed by authorized users.
Now, let’s see how these features can be applied in real-world scenarios:
1 - Mobile and Web Applications: Perfect for building scalable backends for applications that dynamically interact with data, such as social networks or marketplaces.
2 - Real-time Chat: The real-time signing feature makes AppSync ideal for chat platforms, providing instant message delivery.
3 - Collaboration Applications: Allows users to work together in real-time, such as in document editors or file platforms, with dynamic updates for everyone.
4 - Interactive Dashboards: Provides a rich and engaging dashboard experience, enabling efficient queries and dynamic visualizations.
** 5 - Complex service integration: Unifies data from multiple sources into a single API, ideal for applications that require a wide range of integrated information.
6 - OfflineFirst applications:
- Support for offline modes ensures that your applications work without an Internet connection, synchronizing changes as soon as the connection is restored.
- In onlinefirst, the application uses more APIs, simplifying development.
- You worry less about local data, storage, and synchronization. - The cache becomes a temporary resource, which stores lightweight data
Components of a GraphQL API
There are 3 main components in a GraphQL API
Schemas
- They act as a gateway that manages all requests to the server.
- They act as the single endpoint for interfacing with the client.
- They access, process, and relay data from the data source to the client.
Data Sources
- Can include DynamoDB, Lambda, OpenSearch, HTTP endpoints, EventBridge, relational databases, and more.
Resolvers
- Unit of code responsible for determining how a field's data will be resolved during a request.