### Fetch Bins API - Ruby Example Source: https://jsonbin.io/api-reference/collections/bins This Ruby example shows how to fetch bins from a collection using the Fetch Bins API. It uses the net/http and json libraries to send a GET request to the API endpoint. The example sets the X-Master-Key header for authentication and prints the response body. ```Ruby require 'net/http' require 'json' uri = URI("https://api.jsonbin.io/v3/c//bins") res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| req = Net::HTTP::Get.new(uri) req['X-Master-Key'] = '' http.request(req) end puts res.body ``` -------------------------------- ### Fetch Bins API - Python 3 Example Source: https://jsonbin.io/api-reference/collections/bins This Python 3 example demonstrates how to fetch bins from a collection using the Fetch Bins API. It uses the requests library to send a GET request to the API endpoint. The example includes setting the X-Master-Key header for authentication and prints the response text. ```Python import requests url = 'https://api.jsonbin.io/v3/c//bins' headers = { 'X-Master-Key': '' } data = {} req = requests.get(url, json=data, headers=headers) print(req.text) ``` -------------------------------- ### Fetch Bins API - cURL Example Source: https://jsonbin.io/api-reference/collections/bins This cURL example demonstrates how to fetch bins from a collection using the Fetch Bins API. It includes the necessary headers, such as X-Master-Key for authentication, and specifies the GET request method. The API retrieves metadata of bins, including bin ID, creation timestamp, and privacy settings. ```cURL curl -v\ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/c//bins ``` -------------------------------- ### Fetch Bins API - JavaScript Example Source: https://jsonbin.io/api-reference/collections/bins This JavaScript example shows how to fetch bins from a collection using the Fetch Bins API. It utilizes the XMLHttpRequest object to send a GET request to the API endpoint. The example sets the X-Master-Key header for authentication and logs the response to the console. ```JavaScript let req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState == XMLHttpRequest.DONE) { console.log(req.responseText); } }; req.open("GET", "https://api.jsonbin.io/v3/c//bins", true); req.setRequestHeader("X-Master-Key", ""); req.send(); ``` -------------------------------- ### List Collections API - cURL Example Source: https://jsonbin.io/api-reference/collections/list This cURL command demonstrates how to make a GET request to the JSONBin.io List Collections API. It requires the 'X-Master-Key' header for authentication. The API returns metadata for all collections associated with the provided API key. ```bash curl -v \ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/c ``` -------------------------------- ### Create Access Key Request - cURL Source: https://jsonbin.io/api-reference/access-keys/create Example of creating an access key using cURL. It includes necessary headers like Content-Type, X-Master-Key, and X-Key-Name, along with the request payload. ```shell curl -v \ -H "Content-Type: application/json" \ -H "X-Master-Key: " \ -H "X-Key-Name: " \ --request POST \ --data "" \ https://api.jsonbin.io/v3/a ``` -------------------------------- ### GET /l/:date Source: https://jsonbin.io/api-reference/usage-logs/download Downloads usage logs for a specified date. The logs contain details of bins accessed, systems used, and user IPs. ```APIDOC ## GET /l/:date ### Description Downloads usage logs for a specified date. The logs contain details of bins accessed, systems used, and user IPs. ### Method GET ### Endpoint https://api.jsonbin.io/v3/l/:date ### Parameters #### Path Parameters - **date** (string) - Required - The date for which to download logs, in DD/MM/YYYY format. #### Query Parameters None #### Request Body None ### Request Example ``` curl -v \ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/l/26/10/2023 ``` ### Response #### Success Response (200) - A .zip file containing the usage logs for the requested date. #### Response Example (Binary .zip file content) ``` -------------------------------- ### Create Access Key Request - Python 3 Source: https://jsonbin.io/api-reference/access-keys/create Example of creating an access key using Python's requests library. It defines the URL, headers, and data payload for the POST request. ```python import requests url = 'https://api.jsonbin.io/v3/a' headers = { 'Content-Type': 'application/json', 'X-Master-Key': '', 'X-Key-Name': '' } data = req = requests.post(url, json=data, headers=headers) print(req.text) ``` -------------------------------- ### JSON Path Data Access Examples Source: https://jsonbin.io/api-reference/bins/json-path This section provides practical examples of using JSON Paths to extract specific data from the sample JSON. It covers accessing nested fields, filtering arrays based on conditions, and using wildcards and slices. ```JSONPath $.moduleAccess.users[*].firstName | The **firstName** of all users in the module $..country | All **countries** $.moduleAccess.* | All entries in moduleAccess, which are **users** and **userPermissions** $.moduleAccess..age | Extract age of all the users $..users[2] | The third user $..users[(@.length-1)] | The last user via script subscript $..users[-1:] | The last user via slice $..users[0,1] | The first two users via subscript union $..users[:2] | The first two users via subscript array slice $..users[?(@.age)] | Filter all users with age $..users[?(@.age<25)] | Filter all users whose age is lesser than 25 years. $..users[?(@.age==27)] | Filter all users whose age is 27 $..users[?(@.age<25 && @.country=="Australia")] | Filter all Autstralian users whose age is lesser than 25 $..* | All members of JSON structure ``` -------------------------------- ### List Collections API - Ruby Example Source: https://jsonbin.io/api-reference/collections/list This Ruby code snippet utilizes the 'net/http' and 'json' libraries to call the JSONBin.io List Collections API. It constructs a GET request, sets the 'X-Master-Key' header for authentication, and outputs the response body, which includes collection metadata. ```ruby require 'net/http' require 'json' uri = URI("https://api.jsonbin.io/v3/c") res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| req = Net::HTTP::Get.new(uri) req['X-Master-Key'] = '' http.request(req) end puts res.body ``` -------------------------------- ### Sample JSON Data for JSON Path Examples Source: https://jsonbin.io/api-reference/bins/json-path This is a sample JSON object used to demonstrate various JSON Path data access examples. It contains nested objects and arrays, allowing for complex path constructions. ```JSON { "moduleAccess": { "users": [ { "id": "1", "firstName": "Nigel", "lastName": "Rees", "age": 23, "gender": "male", "country": "Australia" }, { "id": "2", "firstName": "Evelyn", "lastName": "Waugh", "age": 28, "gender": "female", "country": "Indonesia" }, { "id": "3", "firstName": "Michelle", "lastName": "White", "age": 27, "gender": "female", "country": "Spain" }, { "id": "4", "firstName": "Aaron", "lastName": "Fernandes", "age": 22, "gender": "male", "country": "India" } ], "userPermissions": { "createGrant": true, "editGrant": false } } } ``` -------------------------------- ### JSON Path Syntax and Examples Source: https://jsonbin.io/api-reference/bins/json-path This section outlines the fundamental syntax rules for JSON Paths, including operators for root, current element, child members, recursion, wildcards, subscripts, unions, slices, and filters. It provides a clear understanding of how to construct JSON Path expressions. ```JSONPath $ | The root object/element @ | The current object/element . | Child member operator .. | Recursive descendant operator; JSONPath borrows this syntax from E4X * | Wildcard matching all objects/elements regardless their names [] | Subscript operator [,] | Union operator for alternate names or array indices as a set [start:end:step] | Array slice operator borrowed from ES4 / Python ?() | Applies a filter (script) expression via static evaluation () | Script expression via static evaluation ``` -------------------------------- ### GET /b//versions/count Source: https://jsonbin.io/api-reference/bins/versions/count Fetches the count of versions for a specified Bin ID. An optional X-Master-Key header can be provided for authentication. ```APIDOC ## GET /b//versions/count ### Description Retrieves the total number of versions created for a specific Bin. ### Method GET ### Endpoint https://api.jsonbin.io/v3/b//versions/count ### Parameters #### Path Parameters - **BIN_ID** (string) - Required - The unique identifier of the Bin. #### Query Parameters None #### Request Body None ### Request Headers - **X-Master-Key** (string) - Optional - Your Core API Access Key for authentication, especially for private bins. ### Request Example ``` curl -v \ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/b//versions/count ``` ### Response #### Success Response (200) - **metadata** (object) - Contains information about the bin. - **id** (string) - The Bin ID. - **versionCount** (integer) - The number of versions for the Bin. - **private** (boolean) - Indicates if the bin is private. #### Response Example ```json { "metadata": { "id": "", "versionCount": 0, "private": true } } ``` #### Error Response (400, 401, 403, 404) - **message** (string) - A message describing the error. #### Error Response Example ```json { "message": "" } ``` ``` -------------------------------- ### List Usage Logs (cURL) Source: https://jsonbin.io/api-reference/usage-logs/list This cURL command demonstrates how to list usage logs from the JSONBin.io API. It requires the 'X-Master-Key' header for authentication and specifies the GET request method to the '/l' endpoint. ```bash curl -v \ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/l ``` -------------------------------- ### List Access Keys API Endpoint and Request Details Source: https://jsonbin.io/api-reference/access-keys/list This section outlines the base URL, the specific route for listing access keys, and the HTTP request method (GET). It also details the required 'X-Master-Key' request header, which is your core API access key. ```text https://api.jsonbin.io/v3 Copy /a Copy GET Copy ``` -------------------------------- ### Read Bin Data using cURL Source: https://jsonbin.io/api-reference/bins/read This cURL command demonstrates how to fetch a specific bin or its version from JSONBin.io. It requires the BIN_ID and optionally BIN_VERSION, along with an X-Master-key for authentication. The request method is GET. ```cURL curl -v \ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/b// ``` -------------------------------- ### List Usage Logs (Ruby) Source: https://jsonbin.io/api-reference/usage-logs/list This Ruby code snippet illustrates how to fetch usage logs from the JSONBin.io API. It uses the 'net/http' library to perform a GET request to the '/l' endpoint, including the required 'X-Master-Key' in the request headers. ```ruby require 'net/http' require 'uri' require 'json' def list_usage_logs(master_key) uri = URI.parse("https://api.jsonbin.io/v3/l") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) request['X-Master-Key'] = master_key begin response = http.request(request) response_body = JSON.parse(response.body) if response.code == "200" puts "Usage Logs: #{response_body['logs']}" return response_body['logs'] else puts "Error: #{response.code} - #{response_body['message']}" return nil end rescue JSON::ParserError => e puts "Error parsing JSON response: #{e.message}" return nil rescue StandardError => e puts "An error occurred: #{e.message}" return nil end end # Example usage: # master_key = "YOUR_X_MASTER_KEY" # Replace with your actual Master Key # logs = list_usage_logs(master_key) # if logs # puts "Successfully retrieved logs." # end ``` -------------------------------- ### List Usage Logs (JavaScript) Source: https://jsonbin.io/api-reference/usage-logs/list This JavaScript code snippet shows how to fetch usage logs using the JSONBin.io API. It utilizes the fetch API to make a GET request to the '/l' endpoint, including the necessary 'X-Master-Key' in the request headers. ```javascript async function listUsageLogs() { const masterKey = "YOUR_X_MASTER_KEY"; // Replace with your actual Master Key try { const response = await fetch('https://api.jsonbin.io/v3/l', { method: 'GET', headers: { 'X-Master-Key': masterKey } }); if (!response.ok) { const errorData = await response.json(); throw new Error(`Error: ${response.status} - ${errorData.message}`); } const data = await response.json(); console.log('Usage Logs:', data.logs); return data.logs; } catch (error) { console.error('Failed to list usage logs:', error); throw error; } } // Example usage: // listUsageLogs().catch(err => console.error(err)); ``` -------------------------------- ### Read Bin Data using Ruby Net::HTTP Source: https://jsonbin.io/api-reference/bins/read This Ruby code snippet uses the Net::HTTP library to fetch bin data from JSONBin.io. It establishes an SSL connection, creates a GET request, sets the 'X-Master-Key' header, and sends the request. The response body is then printed. ```ruby require 'net/http' require 'json' uri = URI("https://api.jsonbin.io/v3/b//") res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| req = Net::HTTP::Get.new(uri) req['X-Master-Key'] = '' http.request() end puts res.body ``` -------------------------------- ### Creating a Bin Source: https://jsonbin.io/api-reference/bins/create This section details how to create a new bin using the JSONBin.io API. It covers required headers, request body format, and potential error scenarios. ```APIDOC ## POST /api/bins ### Description Creates a new bin to store your JSON data. Requires authentication via API key. ### Method POST ### Endpoint /api/bins ### Headers - **Content-Type** (string) - Required - Must be set to `application/json`. - **X-Master-Key** (string) - Required - Your master API key for authentication. - **X-Access-Key** (string) - Required - Your access API key for authentication (ensure it has 'Bins Create' permission). - **X-Bin-Name** (string) - Optional - The desired name for the bin (max 128 characters). - **X-Collection-Id** (string) - Optional - The ID of the collection to which the bin belongs. ### Request Body - **(any JSON object)** - Required - The JSON data to be stored in the bin. Cannot be blank. ### Request Example ```json { "key1": "value1", "key2": 123 } ``` ### Response #### Success Response (200 OK) - **_id** (string) - The unique identifier for the created bin. - **name** (string) - The name of the bin. - **private** (boolean) - Indicates if the bin is private. - **created** (string) - Timestamp of bin creation. #### Response Example ```json { "_id": "60f7b3b3b3b3b3b3b3b3b3b3", "name": "my-first-bin", "private": false, "created": "2023-10-27T10:00:00.000Z" } ``` ### Error Handling - **Bin cannot be blank**: Ensure the request body contains valid JSON. - **X-Bin-Name cannot be blank or over 128 characters**: Provide a valid bin name within the character limit. - **Invalid X-Collection-Id provided**: Verify the Collection ID is correct and belongs to your account. - **Collection not found or the Collection does not belong to the X-Master-Key provided**: Check Collection ID and its association with your keys. - **Schema Doc Validation Mismatch**: Ensure your JSON data conforms to the collection's schema validation rules. - **You need to pass X-Master-Key or X-Access-Key in the header**: Provide a valid API key in the `X-Master-Key` or `X-Access-Key` header. - **X-Access-Key passed does not have permission to create a bin**: Grant 'Bins Create' permission to your Access Key. - **Free users cannot create a record over 100kb**: Upgrade to a Pro plan for larger file uploads or split your JSON. - **Requests exhausted**: Purchase additional requests or upgrade your plan. ``` -------------------------------- ### List Access Keys using cURL, JavaScript, Python, and Ruby Source: https://jsonbin.io/api-reference/access-keys/list Provides code samples for fetching a list of access keys. It demonstrates how to include the necessary 'X-Master-Key' header in requests across different programming languages and tools. ```curl curl -v\ -H "X-Master-Key: " --request GET \ https://api.jsonbin.io/v3/a ``` ```javascript let req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState == XMLHttpRequest.DONE) { console.log(req.responseText); } }; req.open("GET", "https://api.jsonbin.io/v3/a", true); req.setRequestHeader("X-Master-Key", ""); req.send(); ``` ```python import requests url = 'https://api.jsonbin.io/v3/a' headers = { 'X-Master-Key': '' } req = requests.get(url, json=None, headers=headers) print(req.text) ``` ```ruby require 'net/http' require 'json' uri = URI("https://api.jsonbin.io/v3/a") res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| req = Net::HTTP::Get.new(uri) req['X-Master-Key'] = '' http.request(req) end puts res.body ``` -------------------------------- ### List Collections API - Python 3 Example Source: https://jsonbin.io/api-reference/collections/list This Python 3 code uses the 'requests' library to interact with the JSONBin.io List Collections API. It performs a GET request, including the 'X-Master-Key' header for authentication, and prints the response text containing collection metadata. ```python import requests url = 'https://api.jsonbin.io/v3/c' headers = { 'X-Master-Key': '' } data = {} req = requests.get(url, json=data, headers=headers) print(req.text) ``` -------------------------------- ### Create Access Key Payload Sample Source: https://jsonbin.io/api-reference/access-keys/create This is a sample payload used to configure API access keys for Bins API endpoints. It specifies read, update, delete, and create permissions. ```json { "bins": { "read": true, "update": false, "delete": false, "create": true, } } ``` -------------------------------- ### Create Access Key Request - Ruby Source: https://jsonbin.io/api-reference/access-keys/create Shows how to create an access key using Ruby's Net::HTTP library. It constructs the HTTP POST request with appropriate headers and JSON body. ```ruby require 'net/http' require 'json' uri = URI("https://api.jsonbin.io/v3/a") res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| req = Net::HTTP::Post.new(uri) req['Content-Type'] = 'application/json' req['X-Master-Key'] = '' req['X-Key-Name'] = '' req.body = .to_json http.request(req) end puts res.body ``` -------------------------------- ### List Collections API - JavaScript (ES6) Example Source: https://jsonbin.io/api-reference/collections/list This JavaScript code snippet shows how to use the XMLHttpRequest object to call the JSONBin.io List Collections API. It sends a GET request with the necessary 'X-Master-Key' header and logs the response text, which contains collection metadata. ```javascript let req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState == XMLHttpRequest.DONE) { console.log(req.responseText); } }; req.open("GET", "https://api.jsonbin.io/v3/c", true); req.setRequestHeader("X-Master-Key", ""); req.send(); ``` -------------------------------- ### Download Usage Logs using cURL Source: https://jsonbin.io/api-reference/usage-logs/download This cURL command demonstrates how to download usage logs from JSONBin.io for a specified date. It requires the 'X-Master-Key' header for authentication. The response is a .zip file containing the logs. ```shell curl -v \ -H "X-Master-key: " \ --request GET \ https://api.jsonbin.io/v3/l/:date ``` -------------------------------- ### Create XL Bin using Ruby Source: https://jsonbin.io/api-reference/xlbins/create This Ruby code snippet demonstrates creating a large JSON bin using the Net::HTTP library. It sets up the POST request, including necessary headers like 'X-Master-Key' and 'X-Bin-Name'. The JSON file is sent as multipart form data, ensuring correct content type and file handling. ```ruby require 'net/http' require 'uri' require 'json' def create_xl_bin(api_key, file_path, bin_name = nil, is_private = true) uri = URI.parse("https://api.jsonbin.io/v3/xl/b") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request['X-Master-Key'] = api_key request['X-Bin-Private'] = is_private.to_s request['X-Bin-Name'] = bin_name if bin_name boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW" request.set_form_data({ 'xlbin' => File.open(file_path, 'rb') }, boundary) request['Content-Type'] = "multipart/form-data; boundary=#{boundary}" response = http.request(request) if response.code != '200' raise "HTTP Error: #{response.code} - #{response.body}" end JSON.parse(response.body) end # Example usage: # api_key = '' # file_path = '/path/to/your/large_file.json' # bin_name = 'myRubyXLBin' # begin # result = create_xl_bin(api_key, file_path, bin_name, false) # puts result # rescue => e # puts e # end ``` -------------------------------- ### Download Usage Logs using JavaScript Source: https://jsonbin.io/api-reference/usage-logs/download This JavaScript code snippet shows how to download usage logs from JSONBin.io using the fetch API. It includes the necessary 'X-Master-Key' header for authentication. The function returns a Promise that resolves with the .zip file. ```javascript async function downloadUsageLogs(date, masterKey) { const url = `https://api.jsonbin.io/v3/l/${date}`; const headers = { 'X-Master-Key': masterKey }; try { const response = await fetch(url, { method: 'GET', headers: headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const blob = await response.blob(); // You can then process the blob, e.g., create a download link return blob; } catch (error) { console.error('Error downloading logs:', error); throw error; } } // Example usage: // const date = 'DD/MM/YYYY'; // Replace with the desired date // const masterKey = 'YOUR_MASTER_KEY'; // Replace with your actual master key // downloadUsageLogs(date, masterKey) // .then(blob => { // console.log('Logs downloaded successfully. Blob:', blob); // // Further processing of the blob // }) // .catch(error => { // console.error('Failed to download logs.'); // }); ``` -------------------------------- ### Download Usage Logs using Ruby Source: https://jsonbin.io/api-reference/usage-logs/download This Ruby code snippet shows how to download usage logs from JSONBin.io using the 'net/http' library. It includes the necessary 'X-Master-Key' header for authentication. The downloaded .zip file is saved to a specified file path. ```ruby require 'net/http' require 'uri' def download_usage_logs(date, master_key, output_path) uri = URI.parse("https://api.jsonbin.io/v3/l/#{date}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) request['X-Master-Key'] = master_key response = http.request(request) if response.is_a?(Net::HTTPSuccess) File.open(output_path, 'wb') do |file| file.write(response.body) end puts "Usage logs downloaded successfully to #{output_path}" else puts "Error downloading logs: #{response.code} - #{response.message}" end end # Example usage: # date = 'DD/MM/YYYY' # Replace with the desired date # master_key = 'YOUR_MASTER_KEY' # Replace with your actual master key # output_path = 'usage_logs.zip' # download_usage_logs(date, master_key, output_path) ``` -------------------------------- ### Fetch First 10 Bins Source: https://jsonbin.io/api-reference/collections/bins Retrieves the first 10 bin metadata records from a specified collection. Requires authentication with an API key. ```APIDOC ## GET /c//bins ### Description Retrieves the first 10 bin metadata records from a specified collection. Requires authentication with an API key. ### Method GET ### Endpoint `https://api.jsonbin.io/v3/c//bins` ### Parameters #### Path Parameters - **COLLECTION_ID** (string) - Required - The ID of the collection from which to fetch bins. #### Query Parameters None #### Request Body None ### Request Headers - **X-Master-Key** (string) - Required - Your core API access key. - **X-Sort-Order** (string) - Optional - Specifies the sorting order. Accepted values: `ascending`, `descending`. Defaults to `descending`. ### Request Example ```json { "method": "GET", "url": "https://api.jsonbin.io/v3/c//bins", "headers": { "X-Master-Key": "", "X-Sort-Order": "ascending" } } ``` ### Response #### Success Response (200) - **snippetMeta** (object) - Metadata about the bin snippet. - **private** (boolean) - Indicates if the bin is private. - **record** (string) - The ID of the bin record. - **createdAt** (string) - The timestamp when the bin was created. #### Response Example ```json [ { "snippetMeta": {}, "private": true, "record": "", "createdAt": "" }, ... ] ``` #### Error Response (400, 401, 403) - **message** (string) - A message describing the error. #### Error Response Example ```json { "message": "" } ``` ``` -------------------------------- ### List Access Keys API Source: https://jsonbin.io/api-reference/access-keys/list Fetches a list of all access keys created, including their associated permissions and metadata. ```APIDOC ## GET /a ### Description Fetches a list of Access Keys created with permission information for each API endpoint as well as metadata for each of the keys. ### Method GET ### Endpoint https://api.jsonbin.io/v3/a ### Parameters #### Request Headers - **X-Master-Key** (string) - Required - Your Core API Access Key. This key is required to access most API endpoints. ### Request Example ```APIDOC curl -v \ -H "X-Master-Key: " --request GET \ https://api.jsonbin.io/v3/a ``` ### Response #### Success Response (200) - **keyPermissions** (object) - Permissions associated with the access key. - **bins** (object) - Permissions for bin operations. - **update** (boolean) - Whether the key can update bins. - **delete** (boolean) - Whether the key can delete bins. - **create** (boolean) - Whether the key can create bins. - **read** (boolean) - Whether the key can read bins. - **accessKeyId** (string) - The unique identifier for the access key. - **accessKey** (string) - The access key itself. - **metadata** (object) - Metadata for the access key. - **name** (string) - The name of the access key. #### Response Example ```APIDOC [ { "keyPermissions": { "bins": { "update": false, "delete": false, "create": true, "read": true } }, "accessKeyId": "", "accessKey": "", "metadata": { "name": "" } }, ... ] ``` #### Error Response (401, 403) - **message** (string) - A message describing the error. #### Error Response Example ```APIDOC { "message": "" } ``` ``` -------------------------------- ### JSON Bin Update API Success Response Source: https://jsonbin.io/api-reference/bins/update This is an example of a successful response (HTTP status code 200) when updating a JSON bin. It includes the updated 'record' and associated 'metadata' such as the parent ID and privacy status. ```json { "record": { "sample": "Hello World" }, "metadata": { "parentId": "", "private": true } } ``` -------------------------------- ### Read Schema Doc with cURL Source: https://jsonbin.io/api-reference/schema-docs/read This cURL command retrieves a schema document from the jsonbin.io API. It specifies the GET request, content type, and the required X-Master-Key header for authentication. The response includes the schema validation JSON and metadata. ```cURL curl -v\ -H "Content-Type: application/json" \ -H "X-Master-Key: " \ --request GET \ https://api.jsonbin.io/v3/s/ ``` -------------------------------- ### List Usage Logs (Python) Source: https://jsonbin.io/api-reference/usage-logs/list This Python code snippet demonstrates how to retrieve usage logs from the JSONBin.io API. It uses the 'requests' library to send a GET request to the '/l' endpoint, providing the 'X-Master-Key' in the headers for authentication. ```python import requests def list_usage_logs(master_key): url = "https://api.jsonbin.io/v3/l" headers = { "X-Master-Key": master_key } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) data = response.json() print("Usage Logs:", data.get("logs")) return data.get("logs") except requests.exceptions.RequestException as e: print(f"Error fetching usage logs: {e}") if response is not None: try: error_details = response.json() print(f"Error message: {error_details.get('message')}") except requests.exceptions.JSONDecodeError: print("Could not decode error response.") return None # Example usage: # master_key = "YOUR_X_MASTER_KEY" # Replace with your actual Master Key # logs = list_usage_logs(master_key) # if logs: # print("Successfully retrieved logs.") ``` -------------------------------- ### Download Usage Logs using Python Source: https://jsonbin.io/api-reference/usage-logs/download This Python script demonstrates how to download usage logs from JSONBin.io using the 'requests' library. It requires the 'X-Master-Key' header for authentication. The script saves the downloaded .zip file to the local system. ```python import requests def download_usage_logs(date, master_key, output_filename='usage_logs.zip'): url = f'https://api.jsonbin.io/v3/l/{date}' headers = { 'X-Master-Key': master_key } try: response = requests.get(url, headers=headers, stream=True) response.raise_for_status() # Raise an exception for bad status codes with open(output_filename, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print(f'Usage logs downloaded successfully to {output_filename}') return output_filename except requests.exceptions.RequestException as e: print(f'Error downloading logs: {e}') return None # Example usage: # date = 'DD/MM/YYYY' # Replace with the desired date # master_key = 'YOUR_MASTER_KEY' # Replace with your actual master key # download_usage_logs(date, master_key) ``` -------------------------------- ### Create Access Key Request - JavaScript (ES6) Source: https://jsonbin.io/api-reference/access-keys/create Demonstrates how to create an access key using JavaScript's XMLHttpRequest. It sets the required headers and sends the payload to the API endpoint. ```javascript let req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState == XMLHttpRequest.DONE) { console.log(req.responseText); } }; req.open("POST", "https://api.jsonbin.io/v3/a", true); req.setRequestHeader("Content-Type", "application/json"); req.setRequestHeader("X-Master-Key", ""); req.setRequestHeader("X-Key-Name", ""); req.send(''); ``` -------------------------------- ### Add Schema to Collection API - Python 3 Source: https://jsonbin.io/api-reference/collections/schema-docs/add This Python 3 example utilizes the 'requests' library to interact with the Add Schema API. It constructs a PUT request to associate a Schema Document with a collection, specifying the required Master Key in the headers. ```python import requests url = 'https://api.jsonbin.io/v3/c//schemadoc/add' headers = { 'X-Schema-Doc-Id': '', 'X-Master-Key': '' } req = requests.put(url, headers=headers) print(req.text) ``` -------------------------------- ### Read Schema Doc with JavaScript (ES6) Source: https://jsonbin.io/api-reference/schema-docs/read This JavaScript code uses XMLHttpRequest to fetch a schema document from the jsonbin.io API. It sets the request method to GET, specifies the URL, and includes the X-Master-Key header. The response, containing the schema data, is logged to the console. ```JavaScript let req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState == XMLHttpRequest.DONE) { console.log(req.responseText); } }; req.open("GET", "https://api.jsonbin.io/v3/s/", true); req.setRequestHeader("X-Master-Key", ""); req.send(); ``` -------------------------------- ### Authentication Errors Source: https://jsonbin.io/api-reference/bins/read Errors related to missing or invalid authentication credentials. ```APIDOC ## Authentication Required ### Description This error occurs when attempting to access private bins without providing the necessary authentication headers (X-Master-Key or X-Access-Key). ### Method Any (e.g., GET, PUT, DELETE) ### Endpoint Any endpoint for private bins ### Parameters #### Headers - **X-Master-Key** (string) - Required - Your API Key for master access. - **X-Access-Key** (string) - Required - Your API Key for specific access. ### Request Example ``` GET /b/your_bin_id Headers: X-Master-Key: YOUR_MASTER_KEY ``` ### Response #### Error Response (401 or 403) - **message** (string) - "You need to pass X-Master-Key or X-Access-Key in the header to read a private bin." ## Invalid Master Key or Ownership Mismatch ### Description This error indicates that the provided X-Master-Key is invalid, or the bin being accessed does not belong to the account associated with the key. ### Method Any (e.g., GET, PUT, DELETE) ### Endpoint Any endpoint for private bins ### Parameters #### Headers - **X-Master-Key** (string) - Required - Your API Key. ### Response #### Error Response (401 or 403) - **message** (string) - "X-Master-Key is invalid or the bin doesn't belong to your account." ``` -------------------------------- ### Read Bin Data using Python 3 requests Source: https://jsonbin.io/api-reference/bins/read This Python 3 script utilizes the 'requests' library to retrieve bin data from JSONBin.io. It constructs the URL and sets the 'X-Master-Key' header for authentication before sending a GET request. The response text is then printed. ```python import requests url = 'https://api.jsonbin.io/v3/b//' headers = { 'X-Master-Key': '' } req = requests.get(url, json=None, headers=headers) print(req.text) ``` -------------------------------- ### Read Bin Data using JavaScript (ES6) XMLHttpRequest Source: https://jsonbin.io/api-reference/bins/read This JavaScript code snippet uses the XMLHttpRequest object to read a bin from JSONBin.io. It sends a GET request to the specified URL, including the X-Master-Key header for authentication. The response text is logged to the console. ```javascript let req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState == XMLHttpRequest.DONE) { console.log(req.responseText); } }; req.open("GET", "https://api.jsonbin.io/v3/b//", true); req.setRequestHeader("X-Master-Key", ""); req.send(); ```