WebSocket APIs enable real-time, bidirectional communication between web clients and servers, making them ideal for applications that require low latency, such as chat, online gaming, and live streaming. The WebSocket protocol establishes a persistent connection, eliminating the need for repetitive HTTP requests and supporting simultaneous data transmission in both directions. Its lightweight design minimizes overhead, ensuring efficient data exchange, and it is widely supported in modern web browsers, making it a crucial technology for building responsive and interactive web applications that demand real-time updates and communication.
Let’s begin with creating a WebSocket API in API Gateway
Step 1: Create a Lambda function in the Amazon console.
Step 2: Navigate to API Gateway and click on “Create API”, then select “Build API on WebSocket”.
Step 3: Create WebSocket API
- Provide a name to API and give a route selection expression.
- You can add predefined routes and custom routes and attach integration types for the routes added.
- Provide a stage name for deployment, review the changes, and create the API.
Step 4: Now we will add more routes and modify lambda functions.
- We will be adding different routes like disconnect message and default.
- Add routes in the API gateway. Click on the $disconnect and $default. It will ask you the integration type select it as lambda function and select the region and function name.
- To add the custom route message, enter it in the new route key and select the integration type and function name.
- Now click on action and deploy the API.
Step 5: Open your POSTMAN and take the WebSocket URL. Connect the URL and send the message. Once done you can disconnect, or it will disconnect after the default timeout.
In this way, we have learned how we can set up a WebSocket API in API Gateway.