Mojo can call external APIs today by using Python interoperability. That is the most dependable approach while Mojo’s native networking ecosystem is still developing: keep HTTP and JSON handling in a small Python module, then call it from typed Mojo code.
Why use a Python helper?
Mojo’s Python bridge can import Python modules and pass values across the boundary. Python’s standard library already provides mature HTTPS, timeout, and JSON support. Separating the network boundary into one helper also makes failures explicit and keeps the Mojo program easy to test.
1. Create the HTTP helper
Create api_client.py next to the Mojo file:
import json
from urllib.request import Request, urlopen
def fetch_json(url: str) -> dict:
request = Request(url, headers={"User-Agent": "CodeHubJournal/1.0"})
with urlopen(request, timeout=10) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected HTTP status: {response.status}")
return json.load(response)
The timeout prevents a request from waiting forever. urlopen() raises an exception for HTTP errors, DNS failures, TLS problems, and timeouts; the Mojo caller handles those failures at one boundary.
2. Call the helper from Mojo
Create main.mojo:
from std.python import Python
def main() raises:
Python.add_to_path(".")
api_client = Python.import_module("api_client")
try:
var todo = api_client.fetch_json(
"https://jsonplaceholder.typicode.com/todos/1"
)
print("Title:", todo["title"])
print("Completed:", todo["completed"])
except e:
print("Request failed:", e)
Run both files from the same directory:
mojo main.mojo
The stable Mojo 0.26 documentation imports Python from std.python. Nightly builds can change module paths, so check the interoperability documentation that matches your installed channel if this import is unavailable.
Handling real API responses
- Validate required fields instead of assuming every response has the same shape.
- Keep API keys outside source code and never ship a privileged secret in a client application.
- Use an explicit timeout and retry only idempotent requests.
- Do not log access tokens or complete sensitive responses.
- Check the API’s rate limits and status-code contract.
POST requests
For POST requests, encode the payload in the Python helper and set the content type explicitly:
def post_json(url: str, payload: dict) -> dict:
body = json.dumps(payload).encode("utf-8")
request = Request(
url,
data=body,
headers={
"Content-Type": "application/json",
"User-Agent": "CodeHubJournal/1.0",
},
method="POST",
)
with urlopen(request, timeout=10) as response:
return json.load(response)
This design isolates the dynamic Python object handling from the rest of the Mojo application. As Mojo’s native libraries mature, you can replace the helper without changing the higher-level error and data-flow design.


Comment