Category: python
REST API Communication Between Microservices
Published on 22 Aug 2026
Explanation
REST API communication allows independent microservices to exchange data over HTTP. Each service exposes endpoints that other services can consume using HTTP methods such as GET, POST, PUT, and DELETE. For example, an Order Service can call a Product Service to retrieve product information before creating an order. REST APIs usually exchange data in JSON format, making them simple and language-independent. In Python, libraries such as httpx and requests can be used to communicate with REST APIs.
Code:
# Product Service
from fastapi import FastAPI
app = FastAPI()
@app.get('/products/{product_id}')
def get_product(product_id: int):
return {
'id': product_id,
'name': 'Laptop',
'price': 65000
}
# Run:
# uvicorn product_service:app --port 8001
Explanation
The GET method is commonly used when one service needs to retrieve data from another service. Python's httpx library can send an asynchronous GET request to a FastAPI service. In this example, the Order Service calls the Product Service using the product ID and receives product information as JSON. The calling service can then use that information to continue its business logic.
Code:
# Order Service
import httpx
from fastapi import FastAPI
app = FastAPI()
PRODUCT_SERVICE = 'http://localhost:8001'
@app.get('/orders/product/{product_id}')
async def get_product(product_id: int):
async with httpx.AsyncClient() as client:
response = await client.get(
f'{PRODUCT_SERVICE}/products/{product_id}',
timeout=5.0
)
return response.json()
# Run:
# uvicorn order_service:app --port 8002
Explanation
The POST method is used when one service needs to send data to another service, usually to create a new resource. FastAPI uses Pydantic models to validate JSON request data. HTTPX can send the validated data to another service using the json parameter. This pattern is commonly used when an Order Service sends order information to a Payment Service or Notification Service.
Code:
from fastapi import FastAPI
from pydantic import BaseModel
import httpx
app = FastAPI()
class PaymentRequest(BaseModel):
order_id: int
amount: float
@app.post('/payments')
async def create_payment(payment: PaymentRequest):
async with httpx.AsyncClient() as client:
response = await client.post(
'http://localhost:8003/payments',
json=payment.model_dump(),
timeout=5.0
)
return response.json()
Explanation
Service-to-service communication must handle successful responses as well as failures. HTTP status codes indicate whether an operation was successful. A 2xx response generally indicates success, 4xx indicates a client-side error, and 5xx indicates a server-side error. HTTPX provides raise_for_status() to detect unsuccessful HTTP responses. Network errors should also be handled using RequestError. Timeouts are important because a service should not wait indefinitely for another service.
Code:
import httpx
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get('/orders/{order_id}')
async def get_order(order_id: int):
try:
async with httpx.AsyncClient() as client:
response = await client.get(
f'http://localhost:8001/orders/{order_id}',
timeout=5.0
)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError:
raise HTTPException(
status_code=502,
detail='Remote service returned an error'
)
except httpx.RequestError:
raise HTTPException(
status_code=503,
detail='Remote service is unavailable'
)
Explanation
In a real-world e-commerce microservices system, several REST APIs may communicate to complete one business operation. A client sends an order request to the Order Service. The Order Service calls the Product Service to verify the product and then calls the Payment Service to process payment. Each service owns its business logic and can be deployed independently. For production systems, REST communication should be combined with authentication, timeouts, retries, circuit breakers, service discovery, logging, and distributed tracing.
Code:
# E-commerce REST Communication # # Client # | # | POST /orders # v # Order Service # | # | GET /products/101 # v # Product Service # | # | Product details # v # Order Service # | # | POST /payments # v # Payment Service # | # | Payment result # v # Order Service # | # v # Client receives Order Response