gcp cloud run - getting messages from a pub/sub trigger (subscription)
In this setup, we are going to do a quick and dirty setup using source code deployment approach. Our cloud is written in python and then it would read messages from our pub/sub and the prints outs the message. The output will be available in cloud run observability under logs.
And then we would need to have these code in our main.py
import base64
import datetime
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/")
async def pubsub_push(request: Request):
envelope = await request.json()
if not envelope or "message" not in envelope:
return JSONResponse(status_code=400, content={"error": "Bad Request"})
pubsub_message = envelope["message"]
data = ""
if "data" in pubsub_message:
data = base64.b64decode(pubsub_message["data"]).decode("utf-8")
print(f"Received Pub/Sub message: {data}")
return JSONResponse(status_code=200, content=data)
Then we need to add this to our requirements.txt
fastapi[standard]==0.116.1
That's it for the code. Next we will deploy to our gcp cloud run using the following command:-
gcloud run deploy --source .
Next, we will proceed to add a trigger for our cloud run. Goto your newly deployed cloud run and then under trigger, select "Pub/Sub" trigger.
Then create a topic for your pub/sub trigger. So your application will be using Pub/Sub and it uses subscription to pull messages from the a topic we created as shown here:
To generate message, please goto the subscription and then select on "Message" tab and click "Publish Message".
After you publish your message, you can go back to your cloud run -> Observability -> Logs and see the content of your message.
Comments