### Document List API Request Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/00-index.md Example of a GET request to the Document List API. Specify the date, type, and your Subscription-Key. ```http GET /api/v2/documents.json?date=YYYY-MM-DD&type=1&Subscription-Key=KEY ``` -------------------------------- ### Document Fetch API Request Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/00-index.md Example of a GET request to the Document Fetch API. Provide the document ID in the path and specify the type and your Subscription-Key. ```http GET /api/v2/documents/{docID}?type=1&Subscription-Key=KEY ``` -------------------------------- ### Full Document Fetch URL Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md An example of a complete URL for the Document Fetch API, including query parameters for document type and API key. ```http https://api.edinet-fsa.go.jp/api/v2/documents/{docID}?type={type}&Subscription-Key={apiKey} ``` -------------------------------- ### EDINET API Authentication Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/00-index.md All requests require the Subscription-Key query parameter. Replace YOUR_API_KEY with your actual API key. ```text ?Subscription-Key=YOUR_API_KEY ``` -------------------------------- ### Document List API Full URL Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md Example of a full URL for the Document List API, including query parameters for date, type, and API key. ```HTTP https://api.edinet-fsa.go.jp/api/v2/documents.json?date={date}&type={type}&Subscription-Key={apiKey} ``` -------------------------------- ### Query String Example for Document Type 1 Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md Example of a query string to request submission documents (type 1) and authenticate with an API key. ```http ?type=1&Subscription-Key=ZZZ…ZZZ ``` -------------------------------- ### Get Full Document List with jq Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md This cURL command retrieves a full list of documents for a given date and pipes the output to jq for formatted display of sequence number, filer name, and document description. Ensure jq is installed. ```bash curl -X GET \ "https://api.edinet-fsa.go.jp/api/v2/documents.json?date=2023-04-03&type=2&Subscription-Key=YOUR_API_KEY" | \ jq '.results[] | "\(.seqNumber): \(.filerName) - \(.docDescription)"' ``` -------------------------------- ### Error Response Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md An example of an error response from the API, which returns HTTP 200 with a JSON content type and an error message. ```json { "metadata": { "title": "提出された書類を把握するための API", "status": "404", "message": "Not Found" } } ``` -------------------------------- ### Filer Information Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/08-limitations-and-constraints.md Illustrates filer information that may change over time. The EDINET API does not provide historical code mappings. ```json { "edinetCode": "E10001", // May change "secCode": "10000", // May change "filerName": "Old Company" // May change } ``` -------------------------------- ### Test EDINET API Against Multiple Versions Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md Provides an example of how to use parameterized tests to verify API functionality across different versions, ensuring compatibility. ```python # Test suite @pytest.mark.parametrize('version', ['v2', 'v3']) def test_document_fetch(version): client = EdinetClient(api_key, version=version) # Test logic ``` -------------------------------- ### Query String for Full Document Listings (Type 2) Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md Example query string to request full document listings and metadata for a specific date. ```HTTP ?date=2023-04-01&type=2&Subscription-Key=ZZZ…ZZZ ``` -------------------------------- ### Query String for Metadata Only (Type 1) Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md Example query string to request only metadata for a specific date. ```HTTP ?date=2023-04-01&Subscription-Key=ZZZ…ZZZ ``` -------------------------------- ### Get Metadata using cURL Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Use this cURL command to fetch basic metadata for documents on a specific date. Replace YOUR_API_KEY with your actual API key. ```bash curl -X GET \ "https://api.edinet-fsa.go.jp/api/v2/documents.json?date=2023-04-03&Subscription-Key=YOUR_API_KEY" ``` -------------------------------- ### Bulk Document Download with Rate Limiting Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/07-common-patterns.md This Python script demonstrates a recommended approach for downloading all documents within a specified date range. It includes essential features like handling API rate limits by introducing delays between requests and logging progress. Ensure you have the 'requests' library installed and replace 'YOUR_API_KEY' with your actual API key. ```python import time import requests def bulk_download_documents(api_key, start_date, end_date, output_dir): """ Download all documents in a date range. Respects rate limits and logs progress. """ base_url = "https://api.edinet-fsa.go.jp/api/v2" from datetime import datetime, timedelta # Generate business dates current = datetime.strptime(start_date, "%Y-%m-%d") end = datetime.strptime(end_date, "%Y-%m-%d") total_docs = 0 while current <= end: # Skip weekends (only business days) if current.weekday() < 5: date_str = current.strftime("%Y-%m-%d") # Fetch document list list_params = { "date": date_str, "type": "2", "Subscription-Key": api_key } print(f"Fetching {date_str}...") list_response = requests.get( f"{base_url}/documents.json", params=list_params ) list_data = list_response.json() if list_data['metadata']['status'] != '200': print(f" Error: {list_data['metadata']['message']}") current += timedelta(days=1) continue count = list_data['metadata']['resultset']['count'] print(f" Found {count} documents") # Download each document for doc in list_data.get('results', []): doc_id = doc['docID'] # Only download if PDF is available if doc['pdfFlag'] != '1': continue # Rate limiting: wait between requests time.sleep(0.5) # Fetch document doc_params = { "type": "2", # PDF "Subscription-Key": api_key } try: doc_response = requests.get( f"{base_url}/documents/{doc_id}", params=doc_params, timeout=60 ) # Check content type for success if 'application/pdf' in doc_response.headers.get('Content-Type', ''): # Save PDF filename = f"{output_dir}/{doc_id}.pdf" with open(filename, 'wb') as f: f.write(doc_response.content) print(f" Downloaded {doc_id}") total_docs += 1 else: print(f" Error downloading {doc_id}") except Exception as e: print(f" Failed {doc_id}: {e}") current += timedelta(days=1) print(f"Downloaded {total_docs} total documents") # Usage bulk_download_documents( "YOUR_API_KEY", "2023-04-01", "2023-04-30", "documents/" ) ``` -------------------------------- ### Example Form Code Usage Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/04-form-codes.md Illustrates the structure of a form code, its corresponding ordinance code, and its meaning. This format is used to identify document templates and regulatory requirements in API requests. ```text Form Code: "030000" Ordinance Code: "030" Meaning: Securities Report (有価証券報告書) Viewing Period: 10 years ``` -------------------------------- ### Python Connection Pooling with Requests Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/08-limitations-and-constraints.md Reuse HTTP connections for high-volume access to EDINET APIs. This example demonstrates using a requests.Session object to maintain persistent connections. ```python import requests # Create session for connection pooling session = requests.Session() # Reuse across multiple requests for date in dates: response = session.get(url, params=params) # Reuses TCP connection ``` -------------------------------- ### Node.js Backend Proxy for EDINET API Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/08-limitations-and-constraints.md This Node.js example shows how a backend server can act as a proxy to circumvent browser cross-domain restrictions when accessing the EDINET API. The browser makes requests to the backend, which then forwards them to the EDINET API. ```javascript // Backend server app.get('/api/documents', async (req, res) => { const edinet_response = await fetch( `https://api.edinet-fsa.go.jp/api/v2/documents.json?${params}` ); res.json(await edinet_response.json()); }); // Browser code fetch('/api/documents').then(r => r.json()) ``` -------------------------------- ### Securely Logging API Requests Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/05-authentication.md When logging API requests, ensure that API keys are redacted to prevent exposure. This example shows how to replace the key with a placeholder before logging. ```python # ❌ Bad log.debug(f"Request: {full_url}") # URL contains key # ✅ Good log_url = full_url.replace(api_key, "***REDACTED***") log.debug(f"Request: {log_url}") ``` -------------------------------- ### Document Retrieval API Request URL Sample Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/ESE140206.md This is an example of a request URL for retrieving the original document and audit report for a specific document management number. ```http https://api.edinet-fsa.go.jp/api/v2/documents/S1234567?type=1&Subscription-Key=ZZZ…ZZZ ``` -------------------------------- ### Example 401 Response Format Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/05-authentication.md If you receive this JSON response format instead of the standard 401 error, it indicates a different issue, possibly related to parameter formatting, rather than a pure authentication failure. Check your request parameters carefully. ```json { "metadata": { "status": "401", "message": "..." } } ``` -------------------------------- ### Configure API Version in Python Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md Demonstrates how to make the API version configurable using environment variables, which is a best practice for managing API updates. ```python # ✅ Good: Version in configuration API_VERSION = os.getenv('EDINET_API_VERSION', 'v2') BASE_URL = f"https://api.edinet-fsa.go.jp/api/{API_VERSION}" # ❌ Bad: Hard-coded version BASE_URL = "https://api.edinet-fsa.go.jp/api/v2" ``` -------------------------------- ### Abstract EDINET API Calls in Python Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md Shows how to abstract API calls into a class to manage versioning logic internally, promoting cleaner code and easier updates. ```python # ✅ Good: Versioning abstraction class EdinetClient: def __init__(self, api_key, version='v2'): self.api_key = api_key self.version = version def get_documents(self, date, doc_type='1'): # Version-specific logic here pass # ❌ Bad: Direct versioning coupling def get_documents(date, api_key): url = f"https://api.edinet-fsa.go.jp/api/v2/documents.json?..."; ``` -------------------------------- ### 書類取得 API Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/ESE140206.md 指定された書類管理番号に基づいて、特定の書類を取得するための API エンドポイントです。TLS1.2 以上の暗号化通信を使用し、GET メソッドでアクセスします。 ```APIDOC ## GET /api/{バージョン}/documents/{書類管理番号} ### Description 指定された書類管理番号に基づいて、特定の書類を取得します。必要書類パラメータを使用して、取得する書類の種類を指定できます。 ### Method GET ### Endpoint `https://api.edinet-fsa.go.jp/api/{バージョン}/documents/{書類管理番号}` ### Parameters #### Path Parameters - **バージョン** (string) - Required - エンドポイントのバージョンを指定します(例: v2)。 - **書類管理番号** (string) - Required - 取得したい書類の管理番号を指定します。 #### Query Parameters - **type** (integer) - Required - 取得する書類の種類を指定します。 - 1: 提出本文書及び監査報告書 - 2: PDF - 3: 代替書面・添付文書 - 4: 英文ファイル - 5: CSV - **Subscription-Key** (string) - Required - EDINET API の認証に使用する API キーを指定します。 ### Request Example ```http GET https://api.edinet-fsa.go.jp/api/v2/documents/S1234567?type=1&Subscription-Key=ZZZ...ZZZ ``` ### Response #### Success Response (200) - **Content-Type** (string) - レスポンスの Content-Type ヘッダー。取得したデータの形式によって異なります(application/octet-stream, application/pdf, application/json; charset=utf-8)。 #### Response Example レスポンスは、指定された `type` パラメータに基づいたバイナリデータ(ZIP、PDF、JSON など)です。 ``` -------------------------------- ### Document List API Endpoint Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/03-types.md This is the GET endpoint for retrieving a list of documents. It requires a date and an API key, with an optional document type. ```http GET /api/v2/documents.json ``` -------------------------------- ### Set EDINET API Version with Environment Variable Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md Use environment variables to specify the EDINET API version for production systems. This allows for easy switching between versions without modifying application code. ```bash EDINET_API_VERSION=v2 ``` -------------------------------- ### Fetching Multiple Documents (Incorrect vs. Correct) Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/08-limitations-and-constraints.md Demonstrates the incorrect approach of attempting to fetch multiple documents using a list of IDs in a single request and the correct approach of iterating through a list of document IDs to fetch them individually. ```python # ❌ Cannot fetch multiple documents in one request params = { "docIDs": ["S1000001", "S1000002", "S1000003"] } # ✅ Must loop for doc_id in doc_ids: fetch_document(doc_id) ``` -------------------------------- ### Browser JavaScript CORS Error Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/08-limitations-and-constraints.md This JavaScript snippet demonstrates a typical CORS error when attempting to directly access the EDINET API from a browser due to missing Access-Control-Allow-Origin headers. ```javascript // ❌ Will fail with CORS error fetch('https://api.edinet-fsa.go.jp/api/v2/documents.json?...') ``` -------------------------------- ### Invalid API Key Response Example Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/05-authentication.md When an invalid or missing API key is provided, the API returns a JSON object with a 'StatusCode' of 401 and a descriptive message. Note that the HTTP status code may still be 200. ```json { "StatusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." } ``` -------------------------------- ### Fetch Full Document List for a Specific Date Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Fetches a complete list of documents for a given date, specifying '2' for full listings. Includes error handling and iterates through results to print document details. ```python import requests import json api_key = "YOUR_API_KEY" base_url = "https://api.edinet-fsa.go.jp/api/v2/documents.json" # Fetch full document listing for a specific date params = { "date": "2023-04-03", "type": "2", # Full listings "Subscription-Key": api_key } response = requests.get(base_url, params=params) data = response.json() # Check for success if data['metadata']['status'] != '200': print(f"Error: {data['metadata']['message']}") exit(1) # Process documents if 'results' in data: for doc in data['results']: print(f"{doc['seqNumber']}: {doc['filerName']} - {doc['docDescription']}") print(f" Submitted: {doc['submitDateTime']}") print(f" Doc ID: {doc['docID']}") print(f" Form Code: {doc['formCode']}") print() ``` -------------------------------- ### Poll for New Documents with Sequential Number Tracking Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/07-common-patterns.md This Python script continuously polls the EDINET API for new documents submitted on the current date. It uses a state file to track the last seen sequential number, preventing duplicate processing. Ensure you have the 'requests' library installed and replace 'YOUR_API_KEY' with your actual API key. ```python import json import time import requests def poll_for_documents(api_key, state_file="state.json"): """ Continuously poll for new documents. State file tracks last-seen seqNumber per date. """ base_url = "https://api.edinet-fsa.go.jp/api/v2/documents.json" # Load state try: with open(state_file) as f: state = json.load(f) except FileNotFoundError: state = {} # Current date from datetime import datetime today = datetime.now().strftime("%Y-%m-%d") # Initialize state for today if needed if today not in state: state[today] = {"last_seq": 0} # Fetch documents params = { "date": today, "type": "2", "Subscription-Key": api_key } response = requests.get(base_url, params=params) data = response.json() if data['metadata']['status'] != '200': print(f"Error: {data['metadata']['message']}") return [] # Filter for new documents last_seq = state[today]["last_seq"] new_docs = [doc for doc in data.get('results', []) if doc['seqNumber'] > last_seq] if new_docs: # Process new documents processed = [] for doc in new_docs: try: # Assuming process_document is defined elsewhere # process_document(doc, api_key) processed.append(doc['docID']) # Update last seen state[today]["last_seq"] = doc['seqNumber'] except Exception as e: print(f"Error processing {doc['docID']}: {e}") # Save state with open(state_file, "w") as f: json.dump(state, f) return processed return [] # Run continuously # while True: # new_docs = poll_for_documents("YOUR_API_KEY") # if new_docs: # print(f"Processed {len(new_docs)} new documents") # time.sleep(300) # Poll every 5 minutes ``` -------------------------------- ### EDINET API Base URL Structure Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md Illustrates the base URL structure for accessing EDINET API endpoints, including versioning. ```text https://api.edinet-fsa.go.jp/api/{version}/{endpoint} https://api.edinet-fsa.go.jp/api/v2/documents.json https://api.edinet-fsa.go.jp/api/v2/documents/{docID} ``` -------------------------------- ### Fetch Full Document List with Async/Await Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Retrieves a comprehensive list of all documents for a given date, including document type filtering. Uses async/await for cleaner asynchronous code. ```javascript const https = require('https'); async function fetchDocumentList(date, apiKey) { const params = new URLSearchParams({ date: date, type: '2', // Full listings 'Subscription-Key': apiKey }); const url = `https://api.edinet-fsa.go.jp/api/v2/documents.json?${params}`; return new Promise((resolve, reject) => { https.get(url, (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { try { resolve(JSON.parse(data)); } catch (e) { reject(e); } }); }).on('error', reject); }); } async function main() { const apiKey = 'YOUR_API_KEY'; try { const response = await fetchDocumentList('2023-04-03', apiKey); if (response.metadata.status !== '200') { console.error(`Error: ${response.metadata.message}`); return; } console.log(`Found ${response.metadata.resultset.count} documents`); if (response.results) { response.results.slice(0, 5).forEach(doc => { console.log(`${doc.seqNumber}: ${doc.filerName}`); console.log(` ${doc.docDescription}`); }); } } catch (error) { console.error(error); } } main(); ``` -------------------------------- ### Setting API Key Environment Variable Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/05-authentication.md Set your EDINET API key as an environment variable in your terminal session. ```bash export EDINET_API_KEY="your_key_here" ``` -------------------------------- ### Protecting API Keys with Environment Variables Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/05-authentication.md Avoid committing API keys directly into your code. Use environment variables for secure storage and access. ```javascript const API_KEY = "abc123xyz..." const API_KEY = process.env.EDINET_API_KEY ``` -------------------------------- ### Detecting New Documents with SeqNumber Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md Illustrates how to use the `seqNumber` field to identify new document submissions when querying the same date multiple times. This pattern helps in efficiently tracking incremental updates. ```text First query at 12:00: count=13, last seqNumber=13 Second query at 17:00: count=26, last seqNumber=26 New documents are seqNumber 14-26 (submitted 12:00-17:00) ``` -------------------------------- ### Passing the API Key Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/05-authentication.md API keys must be passed as the `Subscription-Key` query parameter in all requests to the EDINET API. The parameter is case-sensitive. ```APIDOC ## GET /api/v2/documents.json ### Description Retrieves documents from the EDINET API. Requires an API key for authentication. ### Method GET ### Endpoint /api/v2/documents.json ### Parameters #### Query Parameters - **date** (string) - Required - The date for which to retrieve documents (e.g., YYYY-MM-DD). - **Subscription-Key** (string) - Required - Your EDINET API key. ### Request Example ``` https://api.edinet-fsa.go.jp/api/v2/documents.json?date=2023-04-11&Subscription-Key=YOUR_API_KEY ``` ### Response #### Success Response (200) - **metadata** (object) - Contains metadata about the response, including status and pagination. - **results** (array) - An array of document objects. #### Response Example ```json { "metadata": { "status": 200, "message": "OK" }, "results": [ { "docID": "...", "submitter": "..." } ] } ``` ### Error Handling #### Invalid or Missing Key Response - **StatusCode** (integer) - 401 - **message** (string) - "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." **Note:** This specific error response has an HTTP status code of 200 but returns a JSON body indicating an authentication failure with a `StatusCode` of 401. ``` -------------------------------- ### Document with Fiscal Period Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/09-document-codes-reference.md Use 'periodStart' and 'periodEnd' for time-bound documents like annual securities reports. Dates follow ISO 8601 format (YYYY-MM-DD). ```json { "docTypeCode": "030", "periodStart": "2022-04-01", "periodEnd": "2023-03-31", "docDescription": "有価証券報告書" } ``` -------------------------------- ### Download Document using cURL Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md This command downloads a specific document using its ID and saves it to a local file named 'document.zip'. Adjust the document ID and type as needed. ```bash curl -X GET \ "https://api.edinet-fsa.go.jp/api/v2/documents/S1000001?type=1&Subscription-Key=YOUR_API_KEY" \ --output document.zip ``` -------------------------------- ### Fetch Financial Document with Error Handling Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Fetches a financial document from the EDINET API with built-in error handling and retry logic for transient network issues or server errors. It raises specific ValueErrors for permanent issues like 'not found' or invalid credentials. ```python import requests import json def fetch_document_safely(api_key, doc_id, doc_type=1, max_retries=3): """Fetch with error handling and retries""" base_url = f"https://api.edinet-fsa.go.jp/api/v2/documents/{doc_id}" for attempt in range(max_retries): try: params = { "type": doc_type, "Subscription-Key": api_key } response = requests.get(base_url, params=params, timeout=30) # Check content type to determine success content_type = response.headers.get('Content-Type', '') if 'application/json' in content_type: # Error response error = response.json() status = error['metadata']['status'] message = error['metadata']['message'] if status == '404': # Document not found - permanent failure raise ValueError(f"Document {doc_id} not found") elif status == '400': # Bad request - permanent failure raise ValueError(f"Bad request: {message}") elif status == '401': # Authentication error - permanent failure raise ValueError("Invalid API key") elif status == '500': # Server error - retry if attempt < max_retries - 1: continue else: raise Exception("Server error (max retries exceeded)") else: raise Exception(f"Unknown error: {message}") # Success - return binary data return response.content except requests.exceptions.Timeout: if attempt < max_retries - 1: continue else: raise except requests.exceptions.ConnectionError: if attempt < max_retries - 1: continue else: raise raise Exception("Failed after max retries") # Usage try: doc_data = fetch_document_safely(api_key, "S1000001") with open("document.zip", "wb") as f: f.write(doc_data) except ValueError as e: print(f"Validation error: {e}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### API Client with Deprecation Handling Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md This Python class provides a backward-compatible way to interact with an API, supporting both old and new parameter names. It maps deprecated parameter names to their current equivalents. ```python class EdinetAPICompat: """API client with deprecation handling""" PARAM_MAPPING = { 'v2': { 'type': 'type', # v2 name }, 'v3': { 'content_type': 'type', # v3 renamed to 'content_type' } } def __init__(self, api_key, version='v2'): self.api_key = api_key self.version = version def get_documents(self, date, type='1', content_type=None): """Support both old and new parameter names""" # Use new param if provided, otherwise convert from old if content_type is not None: actual_type = content_type else: actual_type = type # Backward compat params = { 'date': date, self.PARAM_MAPPING[self.version]['type']: actual_type, 'Subscription-Key': self.api_key } response = requests.get( f"https://api.edinet-fsa.go.jp/api/{self.version}/documents.json", params=params ) return response.json() ``` -------------------------------- ### Standard JSON Response Format Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/01-overview.md Illustrates the structure of successful API responses, including metadata with status and message fields. ```json { "metadata": { "status": "200", "message": "OK" } } ``` -------------------------------- ### Fetch Document File Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/README.md Retrieves the actual document file (ZIP or PDF) for a given document ID. Authentication is required via an API key. ```APIDOC ## GET /documents/{docID} ### Description Fetches a specific EDINET document file (ZIP or PDF) using its unique document ID. This endpoint is used to download the actual disclosure document. ### Method GET ### Endpoint /api/v2/documents/{docID} ### Parameters #### Path Parameters - **docID** (string) - Required - The unique identifier of the document to fetch. #### Query Parameters - **Subscription-Key** (string) - Required - Your API key for authentication. ### Response #### Success Response (200) - The response will be the raw file content of the requested document (ZIP or PDF). #### Response Example (Binary data - ZIP or PDF file content) ``` -------------------------------- ### Filter Documents by Fiscal Period Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/07-common-patterns.md Filters documents based on their fiscal period, either by matching an entire fiscal year or a specific quarter. Requires 'periodStart' and 'periodEnd' to be present. ```python def filter_by_period(documents, year, quarter=None): """Filter documents by fiscal period""" result = [] for doc in documents: if not doc['periodStart'] or not doc['periodEnd']: continue start_year = int(doc['periodStart'][:4]) if quarter is None: # Match entire fiscal year if start_year <= year <= start_year + 1: result.append(doc) else: # Match specific quarter (1-4) # Note: This is simplified; actual logic depends on fiscal calendar result.append(doc) return result # Example fy2023_docs = filter_by_period(all_docs, 2023) ``` -------------------------------- ### Filter EDINET Documents by Form Code Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/09-document-codes-reference.md Filters a list of documents to include only those with specific quarterly report form codes. Assumes a list of document dictionaries named 'docs' is available. ```python # Get all quarterly reports quarterly_forms = ['043000', '043001', '093000', '093001', '082200', '082201'] quarterly_docs = [d for d in docs if d['formCode'] in quarterly_forms] ``` -------------------------------- ### Client-Side Filtering of Documents Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/08-limitations-and-constraints.md Illustrates the limitation of server-side filtering for document listings. The correct approach involves fetching all documents for a given date and then filtering them client-side based on criteria like 'formCode'. ```python # ❌ Not supported # GET /documents.json?date=2023-04-03&formCode=030000 # ✅ Correct approach docs = fetch_documents('2023-04-03') filtered = [d for d in docs if d['formCode'] == '030000'] ``` -------------------------------- ### Implement Document Caching Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/07-common-patterns.md Use this class to cache EDINET API responses locally. It checks for cache validity based on time-to-live (TTL) and file modification time. ```python import os import time import json class DocumentCache: def __init__(self, cache_dir=".cache", ttl_seconds=3600): self.cache_dir = cache_dir self.ttl = ttl_seconds os.makedirs(cache_dir, exist_ok=True) def get_cache_key(self, date): return os.path.join(self.cache_dir, f"documents_{date}.json") def get(self, date): """Get cached documents if fresh""" cache_file = self.get_cache_key(date) if not os.path.exists(cache_file): return None # Check age age = time.time() - os.path.getmtime(cache_file) if age > self.ttl: return None with open(cache_file) as f: return json.load(f) def set(self, date, data): """Cache documents""" cache_file = self.get_cache_key(date) with open(cache_file, 'w') as f: json.dump(data, f) def invalidate(self, date): """Clear cache for a date""" cache_file = self.get_cache_key(date) if os.path.exists(cache_file): os.remove(cache_file) # Usage # cache = DocumentCache() # Check cache first # cached = cache.get('2023-04-03') # if cached: # data = cached # else: # # Fetch from API # # data = fetch_documents('2023-04-03', api_key) # # Cache result # # cache.set('2023-04-03', data) # Process data... ``` -------------------------------- ### Fetch and Extract Submission Document File Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Downloads a submission document (type=1 returns a ZIP file) using its document ID. It checks the response content type for errors and extracts the contents of the ZIP file if successful. ```python import requests import zipfile from io import BytesIO api_key = "YOUR_API_KEY" doc_id = "S1000001" # From document listing base_url = f"https://api.edinet-fsa.go.jp/api/v2/documents/{doc_id}" # Fetch submission document (type=1 returns ZIP) params = { "type": "1", "Subscription-Key": api_key } response = requests.get(base_url, params=params) # Check success using Content-Type header if response.headers.get('Content-Type') == 'application/json; charset=utf-8': # Error response error = response.json() print(f"Error: {error['metadata']['message']}") else: # Success - binary data zip_data = BytesIO(response.content) with zipfile.ZipFile(zip_data) as zf: print("Contents:") for name in zf.namelist(): print(f" {name}") # Extract all files zf.extractall(f"documents/{doc_id}") ``` -------------------------------- ### Check EDINET API Compatibility Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/10-migration-and-versioning.md This Python script periodically checks if the EDINET API has changed by fetching sample data and verifying the presence of expected fields and sections. It's designed to be run daily to detect compatibility issues. ```python def check_api_compatibility(api_key): """ Periodically check if API has changed """ client = EdinetAPI(api_key, version='v2') # Fetch sample data result = client.get_documents('2023-04-03') # Check for expected fields expected_fields = { 'metadata': ['status', 'message', 'resultset'], 'results': ['docID', 'edinetCode', 'submitDateTime'] } issues = [] for section, fields in expected_fields.items(): if section not in result: issues.append(f"Missing section: {section}") continue for field in fields: if section == 'results' and result['results']: if field not in result['results'][0]: issues.append(f"Missing field: {section}[0].{field}") elif section == 'metadata': if field not in result['metadata']: issues.append(f"Missing field: {section}.{field}") return issues # Usage: Run daily if __name__ == "__main__": issues = check_api_compatibility('YOUR_API_KEY') if issues: print("API compatibility issues detected:") for issue in issues: print(f" - {issue}") # Alert operator or log to monitoring system ``` -------------------------------- ### List Submitted Documents Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/README.md Retrieves a list of submitted EDINET documents for a specified date. Authentication is required via an API key. ```APIDOC ## GET /documents.json ### Description Lists submitted EDINET documents for a given date. This endpoint allows users to query for disclosure documents based on their submission date. ### Method GET ### Endpoint /api/v2/documents.json ### Parameters #### Query Parameters - **date** (string) - Required - The date for which to list documents (YYYYMMDD format). - **Subscription-Key** (string) - Required - Your API key for authentication. ### Response #### Success Response (200) - **metadata** (object) - Contains information about the returned list. - **date** (string) - The date for which documents are listed. - **count** (integer) - The number of documents found. - **results** (array) - A list of document objects. - **docID** (string) - The unique identifier for the document. - **submitDateTime** (string) - The date and time the document was submitted. - **filerName** (string) - The name of the filer. - **formCode** (string) - The form code of the document. - **secCode** (string) - The securities code associated with the document. - **currentReport** (boolean) - Indicates if this is the current report. - **edineturl** (string) - The URL to view the document on the EDINET website. - **updateDate** (string) - The date the document was last updated. #### Response Example { "metadata": { "date": "20230101", "count": 5 }, "results": [ { "docID": "S00001G8Z", "submitDateTime": "2023-01-01T09:00:00Z", "filerName": "Example Corp.", "formCode": "1-2", "secCode": "1234", "currentReport": true, "edineturl": "https://disclosure.edinet-fsa.go.jp/...".", "updateDate": "2023-01-01" } ] } ``` -------------------------------- ### Document Fetch Endpoint Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/02-endpoints.md The base endpoint for retrieving document files. Replace {docID} with the document's unique identifier. ```http GET /api/v2/documents/{docID} ``` -------------------------------- ### Query Metadata for Yesterday Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Retrieves metadata for documents submitted on the previous day. Requires an API key and sets up parameters for the API request. ```python import requests from datetime import datetime, timedelta api_key = "YOUR_API_KEY" base_url = "https://api.edinet-fsa.go.jp/api/v2/documents.json" # Query metadata for yesterday yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d") params = { "date": yesterday, "Subscription-Key": api_key } response = requests.get(base_url, params=params) response.raise_for_status() data = response.json() print(f"Status: {data['metadata']['status']}") print(f"Message: {data['metadata']['message']}") print(f"Document count: {data['metadata']['resultset']['count']}") ``` -------------------------------- ### Query Document Metadata with Promises Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md Fetches metadata for documents submitted on a specific date. Requires an API key and uses Node.js 'https' and 'querystring' modules. ```javascript const https = require('https'); const querystring = require('querystring'); const apiKey = 'YOUR_API_KEY'; function getDocumentMetadata(date) { return new Promise((resolve, reject) => { const params = new URLSearchParams({ date: date, 'Subscription-Key': apiKey }); const url = `https://api.edinet-fsa.go.jp/api/v2/documents.json?${params}`; https.get(url, (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { try { const json = JSON.parse(data); resolve(json); } catch (e) { reject(e); } }); }).on('error', reject); }); } // Usage getDocumentMetadata('2023-04-03') .then(data => { console.log(`Status: ${data.metadata.status}`); console.log(`Count: ${data.metadata.resultset.count}`); }) .catch(err => console.error(err)); ``` -------------------------------- ### Check Document Availability with cURL Source: https://github.com/ishizueitaro/edinet-api-docs/blob/main/_autodocs/06-examples.md This cURL command checks for the availability of a document and saves the response headers to '/dev/null'. The '-i' flag is used to include headers in the output, which can be useful for checking the Content-Type. ```bash # Save response headers to check Content-Type curl -i -X GET \ "https://api.edinet-fsa.go.jp/api/v2/documents/S1000001?type=2&Subscription-Key=YOUR_API_KEY" \ -o /dev/null ```