We send and receive messages to let different parts of a program or different programs talk to each other. FastAPI helps us do this easily over the web.
0
0
Sending and receiving messages in FastAPI
Introduction
You want to create a chat app where users send messages to each other.
You need to build an API that accepts data from users and sends back responses.
You want to connect a frontend app with a backend server to exchange information.
You want to log messages sent by users for later review.
You want to build a notification system that sends messages to users.
Syntax
FastAPI
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): content: str @app.post("/send-message") async def send_message(message: Message): return {"received_message": message.content} @app.get("/receive-message") async def receive_message(): return {"message": "Hello from FastAPI!"}
Use @app.post to create an endpoint that receives messages.
Use Pydantic models to define the structure of messages for validation.
Examples
This example shows how to receive a message with a POST request and send back the same message.
FastAPI
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): content: str @app.post("/send-message") async def send_message(message: Message): return {"received_message": message.content}
This example shows how to send a simple message back with a GET request.
FastAPI
@app.get("/receive-message") async def receive_message(): return {"message": "Hello from FastAPI!"}
Sample Program
This program lets you send messages to the server with POST requests and stores them in a list. You can then get all stored messages with a GET request.
FastAPI
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Message(BaseModel): content: str messages = [] @app.post("/send-message") async def send_message(message: Message): messages.append(message.content) return {"status": "Message received", "message": message.content} @app.get("/receive-messages") async def receive_messages(): return {"all_messages": messages}
OutputSuccess
Important Notes
FastAPI automatically converts JSON messages to Python objects and back.
Use async functions to handle requests efficiently.
Remember to run the FastAPI app with a server like Uvicorn to test endpoints.
Summary
FastAPI makes sending and receiving messages easy with simple endpoints.
Use Pydantic models to define message formats clearly.
Store or process messages inside your endpoint functions as needed.