API Gateway and Serverless APIs
# CHAPTER 6
API Gateway and Serverless APIs
1. Introduction
You can build a Cloud Function and expose it directly to the public internet using a Function URL. However, if you are building an enterprise application with 50 different microservices, giving your frontend developers 50 different URLs is a chaotic anti-pattern. Furthermore, exposing raw backend compute logic to the internet without a security shield is dangerous. To solve this, we use an API Gateway. In this chapter, we will learn how an API Gateway unifies, secures, and routes traffic to our serverless backend.2. Learning Objectives
By the end of this chapter, you will be able to:- Define the role of an API Gateway in microservice architecture.
-
Understand routing: Methods (GET, POST) and Resources (
/users,/orders).
- Differentiate between REST APIs and HTTP APIs (in AWS).
- Understand how API Gateway secures backend functions.
- Build a serverless REST API using AWS API Gateway and Lambda.
3. Beginner-Friendly Explanation
Imagine a high-end restaurant.- The Cloud Functions (The Chefs): You have 10 chefs in the kitchen. One makes salad, one grills steak, one bakes cake.
- Without an API Gateway: Customers walk directly into the kitchen, yell at the chefs, and demand food. The chefs spend half their time dealing with customers instead of cooking.
- With an API Gateway (The Waiter): The waiter is the single point of contact. The customer looks at a menu and tells the waiter: "I want the steak." The waiter walks to the kitchen, securely gives the ticket exclusively to the Steak Chef, takes the food, and brings it back to the customer. The customer never talks to the chefs, and the chefs only focus on cooking.
4. The Role of the API Gateway
An API Gateway provides three critical services:-
1.
Unified Entry Point: Instead of 50 URLs, you have one base URL:
api.mycompany.com.
-
2.
Routing: If the request is
GET /users, the Gateway routes it to theGetUserFunction. If the request isPOST /orders, it routes it to theCreateOrderFunction.
- 3. Protection: The Gateway acts as a shield. It can require API Keys, validate authorization tokens (JWTs), and enforce Rate Limiting (e.g., stopping a malicious user who sends 10,000 requests per second) *before* the traffic ever reaches your serverless functions.
5. AWS: REST APIs vs. HTTP APIs
In AWS API Gateway, you have two primary choices for serverless endpoints:- REST APIs: The legacy, fully-featured option. Extremely powerful, supports complex data transformations, API Key management, and usage plans. More expensive and slightly slower.
- HTTP APIs: The modern, streamlined option. Designed specifically for serverless proxies. It is up to 60% faster, 70% cheaper, but lacks some advanced management features.
6. Mini Project: Build a Serverless REST API
Let's connect an API Gateway to the AWS Lambda function we built in Chapter 3.Step-by-Step Tutorial:
*(Assumption: You created the MyHelloWorldAPI Lambda function).*
- 1. Go to the AWS Console and search for API Gateway.
- 2. Scroll down to HTTP API and click Build.
-
3.
Integrations: Click Add integration. Select Lambda. Select your
MyHelloWorldAPIfunction.
-
4.
API name:
MyServerlessGateway. Click Next.
- 5. Configure routes:
-
Method:
GET
-
Resource path:
/hello
-
Integration target:
MyHelloWorldAPI. Click Next.
-
6.
Define stages: Leave the default
$defaultstage. Click Next.
- 7. Click Create.
-
8.
Azure generates an Invoke URL (e.g.,
https://abcdefg.execute-api.us-east-1.amazonaws.com).
-
9.
Copy that URL, paste it into your browser, and add
/helloto the end of it.
-
10.
You will see:
Hello from the Cloud!
*The Magic:* You just built an architecture where a user hits an AWS managed gateway, which securely routes to an AWS managed compute function, which returns a response. Zero servers managed.
7. Real-World Scenarios
A startup launches a mobile game. They build a serverless backend. Suddenly, the game goes viral. A malicious group of hackers tries to crash the game by launching a DDoS attack, sending millions of fake HTTP requests to the login endpoint. Because the startup placed an API Gateway with a strict Rate Limiting policy in front of their Lambda functions, the Gateway absorbs the attack. It blocks the millions of fake requests instantly, returning429 Too Many Requests, protecting the Lambda functions from spinning up and protecting the startup from a massive cloud bill.
8. Best Practices
-
CORS (Cross-Origin Resource Sharing): If you build a React or Angular frontend on a different domain (
mywebsite.com) and it tries to call your API Gateway (api.mycompany.com), the browser will block the request due to security rules. You must explicitly enable CORS on your API Gateway to allow requests from your frontend's domain.
9. Cost Optimization Tips
-
Caching: If you have an endpoint like
GET /daily-newsthat returns the exact same data to 50,000 users today, do not trigger the Lambda function 50,000 times! Enable API Caching on the API Gateway. The Gateway will remember the answer for a set time (e.g., 5 minutes) and instantly return the response to users, saving you massive compute costs.
10. CLI Examples
Deploying an API Gateway via AWS Serverless Application Model (SAM) YAML configuration:11. Exercises
- 1. Explain the architectural advantages of placing an API Gateway between client applications and serverless compute functions.
- 2. Why is enabling Caching at the API Gateway level a critical cost-optimization strategy for Serverless applications?
12. FAQs
Q: Doesn't the API Gateway add latency (delay) to the request? A: Yes, adding a network hop adds latency (usually 5-20 milliseconds). However, the security, routing capabilities, and throttling protection it provides are absolutely mandatory for production systems. The tradeoff is entirely worth it.13. Interview Questions
- Q: Differentiate between an AWS HTTP API and a REST API. In what enterprise scenario would you specifically choose the heavier REST API over the faster HTTP API?
-
Q: A frontend application hosted on S3 is attempting to
POSTdata to an API Gateway endpoint but is receiving a browser-level network error, despite the endpoint testing successfully via Postman. Identify the root cause and the necessary API Gateway configuration to resolve it.