How to Call External APIs in Mojo: HTTP Requests and JSON Parsing

Mojo

Introduction

In modern programming, interacting with external APIs is essential for accessing real-time data, integrating services, and building powerful applications. Mojo, while still evolving, supports basic HTTP operations and JSON handling, enabling API interactions in a Pythonic style. This article shows you how to make HTTP GET requests in Mojo and parse the JSON response with practical code examples.

1. Setting Up HTTP Requests in Mojo

Currently, Mojo doesn’t provide native HTTP libraries. However, because it’s interoperable with Python, you can import and use standard Python modules like requests.

from python import import_module

let requests = import_module("requests")

This gives you access to the full Python requests library from within Mojo.

2. Making a GET Request to an API

Let’s use the public JSONPlaceholder API to fetch a list of posts.

let url = "https://jsonplaceholder.typicode.com/posts"

let response = requests.get(url)

print("Status Code:", response.status_code)
print("Raw Text:", response.text)

The result is a JSON-formatted string. To work with it, you’ll need to parse it into a native structure.

3. Parsing JSON Responses

To parse the JSON string into a usable object (list or dictionary), import the Python json module.

let json = import_module("json")

let data = json.loads(response.text)

for post in data:
    print("Title:", post["title"])

This will output the title of each post in the response.

4. Example: Fetch and Display One Record

let url = "https://jsonplaceholder.typicode.com/users/1"
let res = requests.get(url)
let user = json.loads(res.text)

print("Name:", user["name"])
print("Email:", user["email"])
print("Company:", user["company"]["name"])

5. Error Handling (Optional)

You can optionally handle failed requests using try/except (via Python interop):

try:
    let res = requests.get("https://invalid-url.com")
    let obj = json.loads(res.text)
except err:
    print("Failed to fetch or parse data:", err)

Conclusion

Thanks to Mojo’s Python interoperability, calling external APIs is already practical even in its early stage. By combining the requests and json Python libraries, you can build data-driven applications and integrations within Mojo effortlessly. As the language matures, expect native HTTP support and tighter JSON handling to follow.

Comment

Copied title and URL