Home Coding & Scripting Working with Files, APIs, and JSON in Python

Working with Files, APIs, and JSON in Python

279
0

Most real-world Python programs need to do three things:

  1. Save or read data from a file.
  2. Get information from the internet using an API.
  3. Store and exchange data in JSON format.

Let’s explore each step with examples.


📝 If You Want to Practice the Code

If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):

👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.


🔹 Working with Files

Python makes reading and writing files very simple.

Writing to a File

# open file in write mode ("w")
with open("example.txt", "w") as f:
    f.write("Hello, this is my first file!\n")
    f.write("Python makes it easy.")

This will create (or overwrite) example.txt.

Reading from a File

with open("example.txt", "r") as f:
    content = f.read()

print(content)

👉 Output:

Hello, this is my first file!
Python makes it easy.

🔹 Working with APIs

APIs let your Python program talk to web services. For example, you can fetch weather data, currency rates, or even jokes.

We’ll use the requests library (install it first with pip install requests).

import requests

response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")

if response.status_code == 200:
    print("Data fetched successfully!")
    print(response.text)  # raw response
else:
    print("Error:", response.status_code)

🔹 Working with JSON

Most APIs return data in JSON (JavaScript Object Notation), which looks like a dictionary. Python has a built-in json module.

import requests
import json

response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")

# Convert JSON text into Python dictionary
data = response.json()

print(data["bpi"]["USD"]["rate"])  # print Bitcoin price in USD

👉 Example Output: 42,350.1234

You can also save JSON to a file:

with open("bitcoin.json", "w") as f:
    json.dump(data, f, indent=4)

And load it later:

with open("bitcoin.json", "r") as f:
    loaded_data = json.load(f)

print(loaded_data["chartName"])  # Bitcoin

📝 Mini Task

  1. Write a program that saves three favorite movies into a file.
  2. Use an API (like https://api.agify.io?name=Alice) to fetch data about a name.
  3. Save the response as JSON, then read it back and print one field.

Example:

import requests, json

name = "Alice"
response = requests.get(f"https://api.agify.io?name={name}")
data = response.json()

with open("age.json", "w") as f:
    json.dump(data, f, indent=4)

print("Predicted age for", name, "is", data["age"])

✅ Summary

  • Use open() with "r" (read) or "w" (write) to work with files.
  • Use the requests library to fetch data from APIs.
  • Use the json module to work with JSON data.

With these three skills, you can save data locally, connect your program to the internet, and exchange structured information easily.

Previous articleError Handling in Python
Next articleData Structures in Python (Lists, Dictionaries, Tuples, Sets)
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here