### Install Python Packages for RPK API Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/RPK-API-Beispiele.ipynb Installs necessary Python libraries such as 'requests' and 'pandas' for interacting with the RPK API. This is a prerequisite for running the subsequent examples. ```python %pip install requests pandas ``` -------------------------------- ### Install Python Libraries for Geospatial Data Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/geoportal/Geoportal-Beispiele.ipynb Installs essential Python libraries: geopandas for geospatial data manipulation, requests for making HTTP requests, and folium for map visualization. This is a prerequisite for the subsequent code examples. ```python %pip install geopandas requests folium ``` -------------------------------- ### Fetch Single Feature with Pagination using startIndex and maxFeatures Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/geoportal/Geoportal-Beispiele.ipynb Demonstrates pagination by fetching a single feature starting from a specific index (`startIndex`). This is useful for handling large datasets by retrieving them in smaller chunks. ```python # Start bei Index 5 (`startIndex=5`), d.h. 0-4 werden ausgelassen und holen 1 Feature (`maxFeatures=1`) r = requests.get(wfs_url, params={ 'service': 'WFS', 'version': '1.0.0', 'request': 'GetFeature', 'typename': layer, 'outputFormat': 'GeoJSON', 'startIndex': 5, 'maxFeatures': 1 }) first_page = r.json() first_data = geopandas.GeoDataFrame.from_features(first_page, crs={'init': srs}) first_data ``` -------------------------------- ### Setup and Environment Configuration for Zürich Tourismus API Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/zt-api/ZuerichTourismusAPI-Beispiele.ipynb Installs necessary dependencies and configures the environment for API requests, including SSL handling and helper functions for multi-language field extraction. ```python %pip install requests pandas folium branca anytree import requests import pandas as pd import folium import branca import anytree SSL_VERIFY = False if not SSL_VERIFY: import urllib3 urllib3.disable_warnings() def get_de(field): try: return field['de'] except (KeyError, TypeError): try: return field['en'] except (KeyError, TypeError): return field ``` -------------------------------- ### GET /rpkk-rs/v1/institutionen Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/RPK-API-Beispiele.ipynb Retrieves a list of institutions filtered by a specific department key. ```APIDOC ## GET /rpkk-rs/v1/institutionen ### Description Retrieves institutions associated with a specific department, identified by the 'orgKeyDepartement' parameter. ### Method GET ### Endpoint https://api.stadt-zuerich.ch/rpkk-rs/v1/institutionen ### Parameters #### Query Parameters - **orgKeyDepartement** (string) - Required - The unique key identifying the department (e.g., '25' for Sicherheitsdepartement). ### Request Example GET https://api.stadt-zuerich.ch/rpkk-rs/v1/institutionen?orgKeyDepartement=25 ### Response #### Success Response (200) - **value** (array) - A list of institution objects containing details like bezeichnung, departement, key, and kurzname. #### Response Example { "value": [ { "bezeichnung": "Sicherheitsdepartement Departementssekretariat", "departement": "25", "key": "2500", "kurzname": "SID" } ] } ``` -------------------------------- ### Install Python Dependencies for ParkenDD API Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/parkendd-api/ParkenDD-Beispiel.ipynb Installs the necessary Python packages required to process ParkenDD API data, including requests for HTTP calls, pandas for data manipulation, and geopandas/folium for geospatial visualization. ```bash !pip install requests pandas pendulum geopandas folium ``` -------------------------------- ### Example JSON Response for All Institutions Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/README.md This is an example of the JSON response structure when requesting all institutions. Each institution object includes its 'bezeichnung' (designation), 'departement' (department) with its own details, 'key', and 'kurzname' (short name). ```json { "value": [ { "bezeichnung": "Gemeinde", "departement": { "bezeichnung": "Behörden und Gesamtverwaltung", "key": "10", "kurzname": "BUG" }, "key": "1000", "kurzname": "GZ" }, { "bezeichnung": "Gemeinderat", "departement": { "bezeichnung": "Behörden und Gesamtverwaltung", "key": "10", "kurzname": "BUG" }, "key": "1005", "kurzname": "GRZ" }, { "bezeichnung": "Finanzkontrolle", "departement": { "bezeichnung": "Behörden und Gesamtverwaltung", "key": "10", "kurzname": "BUG" }, "key": "1007", "kurzname": "ZFK" } ] } ``` -------------------------------- ### Search Individuals Response Example (XML) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/README.md An example XML response for searching individuals. It includes a list of hits, each containing a snippet and detailed contact information. The `EM` tags highlight the search term within the snippet. ```XML Marti Peter ... Niggli Peter ... Peter Karin ... Anderegg Peter ... ``` -------------------------------- ### GET /konten Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/README.md Fragt Finanzkonten ab, um detaillierte Informationen zu den Sachkonten zu erhalten. ```APIDOC ## GET /konten ### Description Fragt die Finanzkonten ab. Kann optional nach Departement oder Institution gefiltert werden. ### Method GET ### Endpoint /konten ### Parameters #### Query Parameters - **departement_id** (string) - Optional - Filter nach Departement - **api_key** (string) - Required - Der API-Key für die Authentifizierung. ### Response #### Success Response (200) - **konto_nummer** (string) - Die eindeutige Kontonummer - **bezeichnung** (string) - Bezeichnung des Kontos ### Response Example [ { "konto_nummer": "3000", "bezeichnung": "Löhne des Verwaltungs- und Betriebspersonals" } ] ``` -------------------------------- ### Filter Data by Attribute using EXP_FILTER (QGIS WFS Server) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/geoportal/Geoportal-Beispiele.ipynb This snippet shows how to filter data using the manufacturer-specific `EXP_FILTER` parameter supported by QGIS WFS servers. It allows for more flexible filtering conditions directly in the request URL, such as LIKE operations. The example filters for a 'qname' starting with 'H'. ```python # Filter für Quartier LIKE 'H%' r = requests.get(wfs_url, params={ 'service': 'WFS', 'version': '1.0.0', 'request': 'GetFeature', 'typename': layer, 'outputFormat': 'GeoJSON', 'EXP_FILTER': "qname LIKE 'H%'" }) like_geo = r.json() like_data = geopandas.GeoDataFrame.from_features(like_geo, crs={'init': srs}) ``` -------------------------------- ### Search Official Mandates Response Example (XML) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/README.md An example XML response for searching official mandates. It details the structure of a mandate hit, including personal information, committee details, and duration of the mandate. The `Dauer` element specifies the start and end dates. ```XML "9999-12-31 00:00:00" " l="de-CH" s="1" m="1000" numHits="12" indexName="Behoerdenmandat"> GPK (Geschäftsprüfungskommission) GPK 0bab680addc94a9e83cd184947ee46ce D050DF43 5336 47C2 8BF0 11F0BAB7758A Bucher Gregor eff3cfde35254c71b2370a93b26bf7fc 4084208D-6380-4D59-A426-01231472D25B 2009-02-01T00:00:00.000 9999-12-31T23:59:59.000 01.02.2009 - GPK (Geschäftsprüfungskommission) 0bab680addc94a9e83cd184947ee46ce Kommission 6 6 Sekretariat ... ... ... ... ... ... ... ... ``` -------------------------------- ### GET /departemente Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/README.md Ruft eine Liste der städtischen Departemente ab. ```APIDOC ## GET /departemente ### Description Ruft eine Liste aller verfügbaren Departemente der Stadtverwaltung ab. ### Method GET ### Endpoint /departemente ### Parameters #### Query Parameters - **api_key** (string) - Required - Der API-Key für die Authentifizierung. ### Response #### Success Response (200) - **id** (string) - ID des Departements - **name** (string) - Name des Departements ### Response Example [ { "id": "D1", "name": "Präsidialdepartement" } ] ``` -------------------------------- ### Fetch Account Data by Department and Phase (Python) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/RPK-API-Beispiele.ipynb This Python snippet demonstrates how to retrieve account data for a specific department and budget phase ('RECHNUNG') from the Zurich Open Data API. It uses the `requests` library to make an HTTP GET request and `pandas` to process the JSON response into a DataFrame. Ensure `requests`, `pandas`, and necessary API credentials (headers, SSL verification) are configured. ```python import requests import pandas as pd # Assuming 'dep', 'headers', 'SSL_VERIFY' are defined elsewhere # Example: dep = pd.read_csv('departments.csv') # Or however 'dep' is populated # Example: headers = {'Authorization': 'Bearer YOUR_API_KEY'} # Example: SSL_VERIFY = True key = dep.index[dep.kurzname == 'PRD'].tolist()[0] params = { 'departement': key, 'jahr': 2019, 'betragsTyp': 'RECHNUNG' } r = requests.get( 'https://api.stadt-zuerich.ch/rpkk-rs/v1/sachkonto2stellig', params=params, headers=headers, verify=SSL_VERIFY ) data = r.json() data amountRechnung = pd.DataFrame(data['value']) amountRechnung = amountRechnung.astype({'betrag': 'float64'}) amountRechnung = amountRechnung.astype({'sachkonto': 'int64'}) amountRechnung ``` -------------------------------- ### GET /dokumente/{file-id} Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Downloads specific documents associated with parliamentary business. ```APIDOC ## GET /dokumente/{file-id} ### Description Retrieves a specific document file by its unique identifier. ### Method GET ### Endpoint https://www.gemeinderat-zuerich.ch/dokumente/{file-id} ### Parameters #### Path Parameters - **file-id** (string) - Required - The unique identifier of the document ### Response #### Success Response (200) - **Body** (binary) - The document file content ``` -------------------------------- ### Konten abfragen via HTTP GET Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/README.md Beispiel für den Abruf aller Konten einer spezifischen Dienstabteilung mittels eines HTTP GET Requests. Der Endpunkt erfordert einen orgKey als Parameter und gibt eine JSON-Struktur mit den Kontodetails zurück. ```HTTP GET https://api.stadt-zuerich.ch/rpkk-rs/v1/konten?orgKey=1575 ``` ```JSON { "value": [ { "bezeichnung": "Löhne des Verwaltungs- und Betriebspersonals", "id": 7953, "institution": { "bezeichnung": "Statistik Stadt Zürich", "departement": { "bezeichnung": "Präsidialdepartement", "key": "15", "kurzname": "PRD" }, "key": "1575", "kurzname": "SSZ" }, "kontoNr": "3010 00 000" } ] } ``` -------------------------------- ### Get All Parking Lots in Zurich (JSON Response) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/parkendd-api/README.md This example shows the JSON response when querying for all available parking lots in Zurich. It includes details like the lot's name, address, coordinates, current state (open/closed), and the number of free and total parking spots. The data is updated regularly. ```json { "last_downloaded": "2019-11-18T15:55:02", "last_updated": "2019-11-18T15:51:27", "lots": [ { "address": "Seilergraben", "coords": { "lat": 47.376579, "lng": 8.544743 }, "forecast": false, "free": 6, "id": "zuerichparkgarageamcentral", "lot_type": "", "name": "Parkgarage am Central", "state": "open", "total": 50 }, { "address": "Otto-Schütz-Weg", "coords": { "lat": 47.414848, "lng": 8.540748 }, "forecast": false, "free": 131, "id": "zuerichparkhausaccu", "lot_type": "Parkhaus", "name": "Accu", "total": 194 }, { "address": "Badenerstrasse 380", "coords": { "lat": 47.379458, "lng": 8.509675 }, "forecast": false, "free": 62, "id": "zuerichparkhausalbisriederplatz", "lot_type": "Parkhaus", "name": "Albisriederplatz", "state": "open", "total": 66 }, ... ] } ``` -------------------------------- ### Retrieve Document Metadata and URL (Python) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Demonstrates how to retrieve document metadata and construct download URLs using the OpenDataZurich API. It first extracts document GUIDs and file IDs from a business case, then fetches metadata for a given document GUID and generates a direct download URL for a file ID. ```python # Zuerst: Dokument-GUID aus einem Geschäft holen root_gs = paris_search("geschaeft", 'GRNr any "2023/100"', max_rows=1) hits_gs = get_hits(root_gs) if hits_gs: xml_str = ET.tostring(hits_gs[0], encoding="unicode") # Dokument-GUIDs im XML suchen import re guids = re.findall(r'OBJ_GUID="([a-f0-9]{32})"', xml_str) file_ids = re.findall(r'ID="([a-f0-9]{32}-\d+)"', xml_str) print(f"Gefundene OBJ_GUIDs: {guids}") print(f"Gefundene File-IDs: {file_ids}") ``` ```python def get_document_metadata(doc_guid: str) -> pd.DataFrame: """Ruft Metadaten eines Dokuments anhand der OBJ_GUID ab.""" root = paris_search("dokument", f'ID adj "{doc_guid}"') return hits_to_dataframe(get_hits(root)) def get_document_url(file_id: str) -> str: """Gibt die Download-URL für ein Dokument zurück (ohne /api/ Pfadbestandteil).""" return f"https://www.gemeinderat-zuerich.ch/dokumente/{file_id}" # Beispiel: Metadaten eines bekannten Dokuments # (GUID aus dem Geschäft oben, falls vorhanden) if guids: df_doc_meta = get_document_metadata(guids[0]) print("Dokument-Metadaten:") df_doc_meta.T else: print("Keine Dokument-GUIDs gefunden.") # Beispiel-Download-URL if file_ids: download_url = get_document_url(file_ids[0]) print(f"\nDownload-URL: {download_url}") ``` -------------------------------- ### Example XML Response for Ratspost Search Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/README.md This is an example of the XML response structure returned by the Ratspost search API. It contains details about the search query, hits, and individual 'Ratspost' items, including their dates, titles, and associated documents. ```XML 2023-05-04T00:00:00.000 2023-05-05T00:00:00.000 04.05.2023 2023-05-10T00:00:00.000 614cfb372af649d89520fe3827052898 ... Neue Weisungen 60 f28b1ad5a7634c4f80f765a60e8020c9 2023/173 **Kultur, Konzeptförderung Tanz und Theater, Genehmigung 6-jährige Konzeptförderbeiträge 2024–2029, Aufteilung Rahmenkredit** Weisung, 05.04.2023 ... ... ... ... ... ... ... ``` -------------------------------- ### RPK-API: Fetch Financial Data (Bash) Source: https://context7.com/opendatazurich/opendatazurich.github.io/llms.txt Examples for retrieving financial data from the RPK-API, including departments, institutions, accounts, and amount series. Requires an API key. ```bash # Alle Departemente abrufen curl -H "api-key: vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ" \ "https://api.stadt-zuerich.ch/rpkk-rs/v1/departemente" # Einzelnes Departement (Finanzdepartement, Key 20) curl -H "api-key: vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ" \ "https://api.stadt-zuerich.ch/rpkk-rs/v1/departemente/20" # Alle Institutionen abrufen curl -H "api-key: vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ" \ "https://api.stadt-zuerich.ch/rpkk-rs/v1/institutionen" # Konten einer Institution (Statistik Stadt Zürich, orgKey 1575) curl -H "api-key: vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ" \ "https://api.stadt-zuerich.ch/rpkk-rs/v1/konten?orgKey=1575" # Betragsreihe eines Kontos für Jahr 2019 curl -H "api-key: vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ" \ "https://api.stadt-zuerich.ch/rpkk-rs/v1/betragsreihe?jahre=2019&kontoId=7991" # 2-stellige Sachkonten des Präsidialdepartements (Gemeinderatsbeschluss 2019) curl -H "api-key: vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ" \ "https://api.stadt-zuerich.ch/rpkk-rs/v1/sachkonto2stellig?departement=15&jahr=2019&betragsTyp=GEMEINDERAT_BESCHLUSS" ``` -------------------------------- ### GET /rpkk-rs/v1/konten Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/README.md Retrieves a list of financial accounts filtered by description, account number, or organizational key. ```APIDOC ## GET /rpkk-rs/v1/konten ### Description Queries financial accounts. Supports wildcard searches for account descriptions and numbers. The orgKey can be retrieved via the departments or institutions endpoints. ### Method GET ### Endpoint https://api.stadt-zuerich.ch/rpkk-rs/v1/konten ### Parameters #### Query Parameters - **bezeichnung** (string) - Optional - Description of the accounts. Wildcards (*) are supported. - **kontoNr** (string) - Optional - Account number. Wildcards (*) are supported. Format: 8-digit (pre-2018) or 9-digit (post-2019). - **orgKey** (string) - Optional - Key of the department or institution. ### Request Example GET https://api.stadt-zuerich.ch/rpkk-rs/v1/konten?orgKey=1575 ### Response #### Success Response (200) - **value** (array) - List of account objects containing id, bezeichnung, kontoNr, and institution details. #### Response Example { "value": [ { "bezeichnung": "Löhne des Verwaltungs- und Betriebspersonals", "id": 7953, "institution": { "bezeichnung": "Statistik Stadt Zürich", "key": "1575" }, "kontoNr": "3010 00 000" } ] } ``` -------------------------------- ### GET /api/{index}/{funktion} Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Retrieves parliamentary business data based on specific indices and functions using CQL queries. ```APIDOC ## GET /api/{index}/{funktion} ### Description Retrieves structured parliamentary data such as motions, postulates, or member information. The API uses CQL (Contextual Query Language) for filtering results. ### Method GET ### Endpoint https://www.gemeinderat-zuerich.ch/api/{index}/{funktion} ### Parameters #### Path Parameters - **index** (string) - Required - The data index (e.g., 'geschaeft') - **funktion** (string) - Required - The specific API function to call #### Query Parameters - **q** (string) - Required - CQL query string (e.g., 'GRNr any "2023/*"') - **l** (string) - Required - Language code, use 'de-CH' - **s** (integer) - Optional - Start index for pagination - **m** (integer) - Optional - Max results per page (max 1000) ### Request Example GET https://www.gemeinderat-zuerich.ch/api/geschaeft/search?q=GRNr+any+%222023%2F*%22&l=de-CH ### Response #### Success Response (200) - **Content-Type** (string) - XML (Namespace: http://www.cmiag.ch/cdws/...) #### Response Example ... ``` -------------------------------- ### Setup and Helper Functions for PARIS API Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Initializes the environment by importing necessary libraries for HTTP requests, XML parsing, and data analysis. Sets up global constants and pandas display options for consistent data handling. ```python import requests import xml.etree.ElementTree as ET import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mticker from urllib.parse import quote from datetime import date pd.set_option('display.max_columns', 20) pd.set_option('display.max_colwidth', 80) BASE_URL = "https://www.gemeinderat-zuerich.ch/api" LANG = "de-CH" ``` -------------------------------- ### CQL-Kurzreferenz für die Suche Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Diese Referenz bietet Beispiele für die Verwendung von CQL (Contextual Query Language) zur Suche nach Daten. Sie zeigt, wie Text, Daten, Booleans und Kombinationen von Kriterien für Abfragen verwendet werden können, einschliesslich der Angabe von Sortierkriterien. ```cql # Text-Suche Titel any "Klimaschutz" # mind. ein Wort Titel all "Klimaschutz Massnahmen" # alle Wörter Titel adj "Klimaschutz Massnahmen" # exakte Phrase # Datum Sitzungsdatum_start >= "2024-01-01 00:00:00" Dauer_end > "9999-12-31 00:00:00" # offene Mandate # Boolean Dringlich = true AktivesRatsmitglied = false # Kombiniert GRNr any "2023/*" AND Geschaeftsart any "Motion" # Sortierung seq>0 sortBy Name/sort.ascending ``` -------------------------------- ### GET /dokumente/{guid} Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/README.md Retrieves a specific document file associated with a meeting protocol using its unique file ID. ```APIDOC ## GET /dokumente/{guid} ### Description Downloads a specific document file (e.g., PDF protocol) using the file ID extracted from the search results. ### Method GET ### Endpoint https://www.gemeinderat-zuerich.ch/dokumente/{guid} ### Parameters #### Path Parameters - **guid** (string) - Required - The unique file ID (not the document OBJ_GUID) found in the search response. ### Request Example GET https://www.gemeinderat-zuerich.ch/dokumente/9cf56e38b2db4bb98baffef27ab88ab6-332 ### Response #### Success Response (200) - **File** (Binary) - The requested document file. ``` -------------------------------- ### GET WFS GetFeature Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/geoportal/README.md Fetches specific feature data from a WFS layer in a requested format such as GeoJSON. ```APIDOC ## GET /wfs/geoportal/{dataset} ### Description Requests feature data from the WFS server for a specific layer. ### Method GET ### Endpoint /wfs/geoportal/{dataset}?service=WFS&version=1.1.0&request=GetFeature&typename={layer}&outputFormat=GeoJSON ### Parameters #### Query Parameters - **typename** (string) - Required - The specific layer name to retrieve. - **outputFormat** (string) - Required - The desired data format (e.g., GeoJSON). ### Response #### Success Response (200) - **GeoJSON** (application/json) - The requested geographic features. ``` -------------------------------- ### Access Ratspost API with Python (goifer wrapper) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/README.md This example demonstrates how to use the 'goifer' Python API wrapper to interact with the Ratspost API. The wrapper simplifies data access and manipulation, making it easier to work with the API's entities. ```Python # Example using goifer (assuming installation: pip install goifer) from goifer import Ratspost # Initialize the Ratspost client ratspost_api = Ratspost() # Example: Fetch a specific Ratspost item by ID # Replace 'your_ratspost_id' with an actual ID # try: # item = ratspost_api.get_item('your_ratspost_id') # print(item) # except Exception as e: # print(f"Error fetching item: {e}") # Example: Search Ratspost (similar to the HTTP example) # This would involve constructing a query object for goifer # For detailed examples, refer to the Jupyter Notebook mentioned in the documentation. ``` -------------------------------- ### Set Up API Request Headers Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/RPK-API-Beispiele.ipynb Configures headers for making requests to the RPK API, including setting the 'Accept' header to 'application/json' and providing an 'api-key'. It also includes logic to disable SSL warnings if SSL verification is turned off. ```python if not SSL_VERIFY: import urllib3 urllib3.disable_warnings() headers = { 'Accept': 'application/json', 'api-key': 'vopVcmhIMkeUCf8gQjk1GgU2wK+fKihAdlCl0WKJ' } ``` -------------------------------- ### GET WFS GetCapabilities Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/geoportal/README.md Retrieves the service metadata for a specific WFS endpoint, including supported requests, projections, and data formats. ```APIDOC ## GET /wfs/geoportal/{dataset} ### Description Retrieves the capabilities document for the specified WFS dataset, detailing available layers and server configurations. ### Method GET ### Endpoint /wfs/geoportal/{dataset}?service=WFS&version=1.1.0&request=GetCapabilities ### Parameters #### Path Parameters - **dataset** (string) - Required - The name of the dataset (e.g., Statistische_Quartiere) ### Response #### Success Response (200) - **XML** (application/xml) - A capabilities document containing supported requests, projections, and output formats. ``` -------------------------------- ### Suche und Filterung von Gemeinderatsgeschäften Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Demonstriert die Verwendung von CQL-Abfragen zur Suche nach spezifischen Themen, dringlichen Motionen und Departementszugehörigkeiten. ```python # Suche nach Stichwort root_klima = paris_search("geschaeft", 'Titel any "Klimaschutz"', max_rows=50) df_klima = hits_to_dataframe(get_hits(root_klima)) # Dringliche Motionen 2022-2024 query = '(GRNr any "2022/*" OR GRNr any "2023/*" OR GRNr any "2024/*") AND Geschaeftsart any "Motion" AND Dringlich = true' root_dringl = paris_search("geschaeft", query, max_rows=200) # Filter nach Departement query_fd = 'GRNr any "2024/*" AND Departement any "Finanzdepartement"' root_fd = paris_search("geschaeft", query_fd, max_rows=200) ``` -------------------------------- ### Find Businesses from 2016 using API Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/README.md Example of how to query the API to find business items initiated within the year 2016. This demonstrates date range filtering and sorting. It also highlights the importance of pagination parameters 's' and 'm'. ```HTTP GET http://www.gemeinderat-zuerich.ch/api/geschaeft/searchdetails?q=beginn_start > "2016-01-01 00:00:00" AND beginn_start < "2017-01-01 00:00:00" sortBy beginn_start/sort.ascending&l=de-CH&s=1&m=100 ``` -------------------------------- ### Visualisierung der Top-Einreichenden (Python) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Dieses Snippet visualisiert die Top-15 aktivsten Einreichenden von Vorstössen zwischen 2022 und 2026. Es erstellt eine Pivot-Tabelle, die Personen den Jahren zuordnet und die Anzahl der Vorstösse zählt. Die Daten werden dann als gestapelte horizontale Balkengrafik dargestellt, wobei die Jahre als Legende dienen und die X-Achse die Anzahl der Vorstösse anzeigt. ```python import matplotlib.pyplot as plt import matplotlib.ticker as mticker if eu_cols and "Jahr" in df_vs.columns: eu_col = eu_cols[0] # Top-15 Einreichende insgesamt (2022-2026) top_personen = df_vs[eu_col].value_counts().head(15).index # Pivot: Person (Zeilen) x Jahr (Spalten) df_pivot = ( df_vs[df_vs[eu_col].isin(top_personen)] .groupby([eu_col, "Jahr"]) .size() .unstack("Jahr", fill_value=0) ) # Sicherstellen, dass alle Jahre 2022-2026 vorhanden for j in vorst_jahre: if j not in df_pivot.columns: df_pivot[j] = 0 df_pivot = df_pivot[sorted(df_pivot.columns)] # Sortierung nach Gesamtzahl (aufsteigend für horizontale Balken) df_pivot = df_pivot.loc[df_pivot.sum(axis=1).sort_values(ascending=True).index] fig, ax = plt.subplots(figsize=(10, 8)) df_pivot.plot(kind="barh", stacked=True, ax=ax, colormap="viridis", width=0.75) ax.set_xlabel("Anzahl Vorstösse") ax.set_title("Top-15 aktivste Einreichende – Vorstösse 2022–2026") ax.legend(title="Jahr", loc="lower right") ax.xaxis.set_major_locator(mticker.MaxNLocator(integer=True)) plt.tight_layout() plt.show() elif eu_cols: print("Jahr-Spalte fehlt.") else: print("Erstunterzeichner-Spalte nicht gefunden.") ``` -------------------------------- ### Query WFS for Feature Count using resultType=hits Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/geoportal/Geoportal-Beispiele.ipynb Sends a 'GetFeature' request with `resultType='hits'` to get the total number of features available for a layer without retrieving the actual feature data. This is useful for understanding the dataset size. ```python # Start bei Index 5 (`startIndex=5`), d.h. 0-4 werden ausgelassen und holen 1 Feature (`maxFeatures=1`) r = requests.get(wfs_url, params={ 'service': 'WFS', 'version': '1.0.0', 'request': 'GetFeature', 'typename': layer, 'resultType': 'hits' }) r.content ``` -------------------------------- ### Filter Accounts by Prefix in Python Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/RPK-API-Beispiele.ipynb This Python snippet uses the pandas library to filter a DataFrame of accounts. It selects rows where the 'kontoNr' (account number) starts with a specific prefix, demonstrating how to find aggregated accounts based on their hierarchical numbering. The input is expected to be a pandas DataFrame named 'dav_accounts'. ```python dav_accounts[dav_accounts.kontoNr.str.startswith('3010 00')] ``` -------------------------------- ### Accessing RPK API Data with Python Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/rpk-api/README.md Demonstrates how to fetch and process data from the RPK API using Python. This example is suitable for use within Jupyter Notebooks and requires no external libraries beyond standard Python capabilities for data handling. ```python import requests url = "https://www.stadt-zuerich.ch/ogd/2019/api/v1/budgets/" params = { "institution": "1530", "jahr": 2019, "sachkonto": "31" } response = requests.get(url, params=params) if response.status_code == 200: data = response.json() print(data) else: print(f"Error: {response.status_code}") ``` -------------------------------- ### Load Large Datasets with Pagination (Python) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/paris-api/paris_api_gemeinderat_zuerich_tutorial.ipynb Illustrates how to handle large datasets from the API using pagination. It utilizes a helper function `load_all_pages` to fetch all business cases from 2020 to the current year, handling the API's limit of 1000 results per request. ```python # Alle Geschäfte seit 2020 bis aktuelles Jahr laden (paginiert) aktuelles_jahr = date.today().year startjahr = 2020 jahres_query = " OR ".join(f'GRNr any "{j}/*"' for j in range(startjahr, aktuelles_jahr + 1)) df_alle = load_all_pages( index="geschaeft", query=jahres_query, page_size=500, max_total=3000, ) print(f"\nGeladene Datensätze: {len(df_alle):,}") df_alle.head(3) ``` -------------------------------- ### Get Historical Parking Data for a Specific Lot (JSON Response) Source: https://github.com/opendatazurich/opendatazurich.github.io/blob/master/parkendd-api/README.md This example demonstrates how to retrieve historical parking data for a specific parking lot over a defined timespan. The response contains an array of objects, each with the number of free parking spots and the timestamp of the measurement. The API allows querying up to 7 days per request. ```json { "data": [ { "free": 62, "timestamp": "2024-09-24T00:05:08" }, { "free": 62, "timestamp": "2024-09-24T00:10:03" }, { "free": 62, "timestamp": "2024-09-24T00:45:03" }, { "free": 62, "timestamp": "2024-09-24T00:55:08" }, { "free": 62, "timestamp": "2024-09-24T01:10:08" }, { "free": 62, "timestamp": "2024-09-24T01:20:08" }, { "free": 62, "timestamp": "2024-09-24T01:25:03" }, { "free": 62, "timestamp": "2024-09-24T01:30:03" }, { "free": 62, "timestamp": "2024-09-24T01:35:03" }, ... ] } ```