🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 11
TEC-WEB46-03 · Lesson 11 · 14 clock hours · lab

Python Scripting for Automation and API Consumption

Objective. Students write Python scripts that automate a file-system task using os and shutil modules and consume a public REST API using the requests library, parsing JSON responses into Python data structures

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Python Scripting for Automation and API Consumption

Python is one of the most widely used languages for scripting, automation, and web-connected work. In this lab you will write two practical scripts and one short technical document. By the end you will be able to automate file-system tasks safely and pull live data from the internet using a public REST API.

Working with the File System: os and shutil

The `os` module gives your script access to the operating system: listing directories, checking whether a path exists, creating folders, and reading file metadata. The `shutil` module handles higher-level file operations such as copying and moving files.

Key functions you will use:

When you move files you may encounter `PermissionError` — for example, a file owned by another user or marked read-only. Always wrap file operations in a `try/except PermissionError` block and log the error rather than letting the script crash. A script that crashes halfway through a reorganization can leave a directory in a broken state, which is why error handling is a safety concern, not just a nice-to-have.

Logging Actions with the logging Module

Use Python's built-in `logging` module to record what your script does. Configure a `FileHandler` with a timestamped filename so each run produces its own log. A typical setup calls `logging.basicConfig()` with `filename`, `level=logging.INFO`, and a `format` string that includes `%(asctime)s`. Log every move, every directory created, and every permission error. A readable log is your audit trail — reviewers and future-you will rely on it.

What Is a REST API?

REST (Representational State Transfer) is a design style for web services. A REST API exposes resources at URLs called endpoints. Clients request resources using standard HTTP methods; the most common for reading data is GET. The server responds with a status code and, usually, a body formatted as JSON.

JSON (JavaScript Object Notation) is a plain-text format that represents data as key-value pairs inside curly braces (`{}`), arrays inside square brackets (`[]`), and nested combinations of both. Python's `json` module — and the `requests` library — can turn a JSON string directly into Python dictionaries and lists, which you can then work with using normal Python syntax.

The requests Library

`requests` is not part of the Python standard library; install it with `pip install requests`. It simplifies HTTP so you can focus on your data rather than raw socket code.

A basic GET request looks like this:

```python

import requests

response = requests.get("https://api.open-meteo.com/v1/forecast",

params={"latitude": 40.71, "longitude": -74.01,

"current_weather": True})

response.raise_for_status() # raises an exception for 4xx/5xx codes

data = response.json() # parses JSON body into a Python dict

print(data["current_weather"]["temperature"])

```

`response.status_code` holds the HTTP status code (200 = OK, 404 = Not Found, 500 = Server Error, and so on). `raise_for_status()` is a convenient shortcut that raises an `HTTPError` when the server reports an error code. Wrap your request in a `try/except requests.exceptions.HTTPError` block and print a helpful message instead of a raw traceback.

HTTP Status Codes You Must Handle

| Code | Meaning | Suggested user message |

|------|---------|------------------------|

| 200 | OK | (proceed normally) |

| 404 | Not Found | "The requested resource was not found." |

| 429 | Too Many Requests | "Rate limit reached — wait and retry." |

| 500 | Internal Server Error | "Server error — try again later." |

JSON to Python Data Structures

When `response.json()` runs, it maps JSON types to Python types automatically:

You navigate nested structures with chained key lookups: `data["current_weather"]["temperature"]`.

Safety and Good Practice Notes

Key terms9

REST APIA web service design style where resources are accessed at URLs using standard HTTP methods; GET, POST, PUT, and DELETE are the most common, and responses are typically formatted as JSON.
JSON (JavaScript Object Notation)A lightweight plain-text data format that represents data as key-value pairs and arrays; it is language-independent and maps directly to Python dictionaries and lists when parsed.
requests libraryA third-party Python package that simplifies making HTTP requests; its get() function sends an HTTP GET request and returns a Response object containing the status code and body.
os moduleA Python standard-library module that provides functions for interacting with the operating system, including listing directories, joining paths, and checking whether files or folders exist.
shutil moduleA Python standard-library module that provides high-level file operations such as moving, copying, and deleting files and directory trees.
HTTP status codeA three-digit number returned by a web server in response to an HTTP request; codes in the 200s indicate success, 400s indicate client errors, and 500s indicate server errors.
PermissionErrorA Python built-in exception raised when a script attempts a file-system operation it does not have operating-system permission to perform, such as moving a file owned by another user.
raise_for_status()A method on a requests Response object that automatically raises an HTTPError exception if the server returned a 4xx or 5xx status code, simplifying error handling.
logging moduleA Python standard-library module that provides a flexible framework for recording messages from a script to the console, a file, or other destinations, with configurable severity levels.
In class: File automation script: students write a Python script that scans a directory of mixed files, organizes them into subdirectories by file extension, logs a summary of actions taken to a timestamped log file, and handles permission errors gracefully · API consumption lab: students use the requests library to query a free public REST API (such as the Open Meteo weather API or a similarly open, key-free API), parse the JSON response, and display formatted results — they handle HTTP error codes with appropriate messages · Students write a brief technical document (one page) explaining what a REST API is, what JSON is, how the requests library sends an HTTP GET request, and how response data maps to Python dictionaries — this document goes into their lab log
Materials: Python docs (os, shutil, json modules), requests library docs (requests.readthedocs.io), free public REST API endpoint, VS Code, student lab log template
Check: File automation script correctly organizes files and writes a log without crashing on permission errors; API script fetches and displays real data and handles at least one error code; technical document is accurate — pass requires all three deliverables accepted

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Operating System Concepts / File Management
1. Which Python standard-library function creates a directory and all missing parent directories without raising an error if the directory already exists?
Programming Concepts / Error Handling
2. A student's file-automation script crashes with a PermissionError when it tries to move a read-only file. What is the correct fix?
Programming / Python Fundamentals
3. After calling response = requests.get(url), a student wants to convert the JSON response body into a Python dictionary. Which expression is correct?
Networking Concepts / HTTP
4. What does an HTTP status code of 404 indicate?
Programming / Python Fundamentals
5. A REST API returns the following JSON: {"city": "Denver", "temp_c": 15.2, "conditions": ["sunny", "windy"]}. After parsing with response.json(), how does a student access the string "windy"?
Operating System Concepts / File Management
6. A student needs to split the filename "report_2024.pdf" to get the extension ".pdf" using the os module. Which call is correct?
Security Concepts / Secure Coding
7. Which of the following is the best practice for storing an API key in a Python script intended to be shared on a team version-control repository?
Programming / Python Fundamentals
8. A student uses response.raise_for_status() inside a try block. The server returns a 500 status code. What happens next?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.