Skip to content

Update Fareham Borough Council JSON interface and parsing#1723

Merged
robbrad merged 2 commits into
robbrad:dec_releasefrom
gcareid:master
Dec 7, 2025
Merged

Update Fareham Borough Council JSON interface and parsing#1723
robbrad merged 2 commits into
robbrad:dec_releasefrom
gcareid:master

Conversation

@gcareid
Copy link
Copy Markdown
Contributor

@gcareid gcareid commented Nov 17, 2025

The JSON interface has changed (as well as its input parameters).

Summary by CodeRabbit

  • Bug Fixes
    • Updated bin collection data retrieval with current API parameters
    • Enhanced garden waste bin detection and date parsing accuracy
    • Reorganized data extraction process for improved bin collection information retrieval

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 17, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The Fareham Borough Council integration is updated to use a 2025 API endpoint variant with revised request parameters. The bin collection data extraction key is changed, and Garden waste bin handling is refactored from inline creation to a separate detection pass over the API response.

Changes

Cohort / File(s) Change Summary
Fareham Borough Council API & Data Extraction
uk_bin_collection/uk_bin_collection/councils/FarehamBoroughCouncil.py
API request parameters updated from list="DomesticBinCollections" with Road="" to list="DomesticBinCollections2025on". Extraction key changed from DomesticBinDay to BinCollectionInformation. Garden waste bin detection refactored from inline creation within the collection loop to a separate pass that checks for GardenWasteBinDay in the response. Date parsing logic enhanced to handle Garden waste dates explicitly.

Sequence Diagram(s)

sequenceDiagram
    participant API as Fareham API
    participant Parser as FarehamBoroughCouncil
    participant Data as Bin Data

    Parser->>API: Request DomesticBinCollections2025on<br/>(Road or Postcode)
    API-->>Parser: BinCollectionInformation response
    
    rect rgb(230, 245, 255)
        Note over Parser: Parse Regular Bins
        loop For each bin in rows[0]
            Parser->>Data: Extract bin type & date
            Parser->>Data: Add to bins list
        end
    end
    
    rect rgb(240, 255, 240)
        Note over Parser: Detect Garden Waste
        alt GardenWasteBinDay present
            Parser->>Data: Parse Garden date
            Parser->>Data: Add Garden bin entry
        end
    end
    
    Parser->>Data: Sort bins by collectionDate
    Parser-->>Parser: Return parsed bins
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Areas requiring attention:
    • Verify API parameter changes are backward-compatible or that legacy endpoint is properly retired
    • Confirm extraction key rename (DomesticBinDayBinCollectionInformation) matches actual API response structure
    • Test Garden waste detection logic to ensure GardenWasteBinDay field presence/absence is correctly handled
    • Validate date parsing for both regular and Garden waste bins produces consistent datetime objects
    • Check edge cases: missing postcode, no Garden waste data, date parsing failures

Suggested reviewers

  • dp247

Poem

🐰 The bin day bard hops and cheers,
New twenty-twenty-five appears!
Garden waste now gets its space,
In separate passes, with style and grace. 🗑️✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: updating the JSON interface and parsing for Fareham Borough Council, which aligns with the changeset that modifies API parameters, extraction keys, and data parsing logic.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented Nov 17, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.79%. Comparing base (37c8a80) to head (c33ef98).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1723   +/-   ##
=======================================
  Coverage   86.79%   86.79%           
=======================================
  Files           9        9           
  Lines        1136     1136           
=======================================
  Hits          986      986           
  Misses        150      150           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37c8a80 and c33ef98.

📒 Files selected for processing (1)
  • uk_bin_collection/uk_bin_collection/councils/FarehamBoroughCouncil.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.14.4)
uk_bin_collection/uk_bin_collection/councils/FarehamBoroughCouncil.py

59-59: re may be undefined, or defined from star imports

(F405)


60-60: datetime may be undefined, or defined from star imports

(F405)


63-63: date_format may be undefined, or defined from star imports

(F405)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Parity Check (3.12, 1.8.4)
  • GitHub Check: Run Integration Tests (3.12, 1.8.4)
  • GitHub Check: Run Unit Tests (3.12, 1.8.4)
🔇 Additional comments (1)
uk_bin_collection/uk_bin_collection/councils/FarehamBoroughCouncil.py (1)

38-38: Response key updated to match new API.

The extraction key has been changed from "DomesticBinDay" to "BinCollectionInformation", which aligns with the updated API endpoint.

Comment on lines +24 to +25
"list": "DomesticBinCollections2025on",
"Road or Postcode": user_postcode,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify the updated API parameters work correctly.

The API list parameter has been updated to "DomesticBinCollections2025on" and the postcode parameter renamed to "Road or Postcode". Please ensure these changes match the council's actual API requirements and test with real postcodes to confirm the endpoint returns valid data.

Run the following script to test the API response:


🏁 Script executed:

#!/bin/bash
# Description: Test the Fareham Borough Council API with sample postcode

# Test with a sample Fareham postcode
curl -s "https://www.fareham.gov.uk/internetlookups/search_data.aspx?type=JSON&list=DomesticBinCollections2025on&Road%20or%20Postcode=PO14%201AA" | jq '.data.rows[0] | keys'

Length of output: 64


🏁 Script executed:

#!/bin/bash
# Get raw API response without jq filtering to see actual structure
echo "=== Raw API Response ===" 
curl -s "https://www.fareham.gov.uk/internetlookups/search_data.aspx?type=JSON&list=DomesticBinCollections2025on&Road%20or%20Postcode=PO14%201AA" | head -c 500

echo -e "\n\n=== Response Headers and Status ===" 
curl -s -w "HTTP Status: %{http_code}\n" -o /dev/null "https://www.fareham.gov.uk/internetlookups/search_data.aspx?type=JSON&list=DomesticBinCollections2025on&Road%20or%20Postcode=PO14%201AA"

Length of output: 528


🏁 Script executed:

#!/bin/bash
# Examine the FarehamBoroughCouncil.py file to understand response structure expectations
cat uk_bin_collection/uk_bin_collection/councils/FarehamBoroughCouncil.py

Length of output: 2674


Two issues require attention: inconclusive API parameter verification and critical error handling gap in garden waste parsing.

The API parameters appear syntactically correct based on response structure, but cannot be fully validated externally without a valid postcode in the system. Please manually test these changes with a real Fareham postcode to confirm the API returns valid bin data.

More critically, the garden waste handling at lines 56-65 has a dangerous bug:

results = re.findall(r'(\d{1,2}/\d{1,2}/\d{4})', value)
collection_date = datetime.strptime(results[0], "%d/%m/%Y")  # Line 61: IndexError if regex fails

This will raise IndexError if the regex finds no dates. Fix by adding an empty check like the main parsing logic does at lines 44-49, or skip entries with no dates. Additionally, the garden waste section lacks the "today" handling present in the main collection loop (line 46)—add that logic or document why it's not needed.

Comment on lines +56 to +65
# Look for garden waste key
for key, value in bin_data["rows"][0].items():
if key.startswith("GardenWasteBinDay"):
results = re.findall(r'(\d{1,2}/\d{1,2}/\d{4})', value)
collection_date = datetime.strptime(results[0], "%d/%m/%Y")
garden_data = {
"type": "Garden",
"collectionDate": collection_date.strftime(date_format),
}
data["bins"].append(garden_data)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add error handling and "today" support for garden waste parsing.

The garden waste parsing logic has several issues:

  1. Line 60: Accessing results[0] without checking if the regex matched anything will raise an IndexError if the garden waste date format is unexpected.
  2. Line 59: The regex doesn't handle "today" as a date value, unlike the main parsing loop (lines 44-47), creating inconsistent date handling.
  3. Lines 57-58: If multiple keys start with "GardenWasteBinDay", multiple garden entries will be appended without validation.

Apply this diff to add proper error handling and consistent date parsing:

 # Look for garden waste key
 for key, value in bin_data["rows"][0].items():
     if key.startswith("GardenWasteBinDay"):
-        results = re.findall(r'(\d{1,2}/\d{1,2}/\d{4})', value)
-        collection_date = datetime.strptime(results[0], "%d/%m/%Y")
-        garden_data = {
-            "type": "Garden",
-            "collectionDate": collection_date.strftime(date_format),
-        }
-        data["bins"].append(garden_data)
+        results = re.findall(r'(\d{1,2}/\d{1,2}/\d{4}|today)', value)
+        if results:
+            if results[0] == "today":
+                collection_date = datetime.today()
+            else:
+                collection_date = datetime.strptime(results[0], "%d/%m/%Y")
+            garden_data = {
+                "type": "Garden",
+                "collectionDate": collection_date.strftime(date_format),
+            }
+            data["bins"].append(garden_data)
+        break  # Only process the first matching key
🧰 Tools
🪛 Ruff (0.14.4)

59-59: re may be undefined, or defined from star imports

(F405)


60-60: datetime may be undefined, or defined from star imports

(F405)


63-63: date_format may be undefined, or defined from star imports

(F405)

@robbrad robbrad changed the base branch from master to dec_release December 7, 2025 10:18
@robbrad robbrad merged commit 3aacc58 into robbrad:dec_release Dec 7, 2025
3 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Dec 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants