### Setup and Run Restfox Web Standalone Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Clones the Restfox repository, installs dependencies for the UI and web-standalone packages, builds the web-standalone version, and starts the application. This process allows running Restfox as a self-contained web app. ```bash git clone https://github.com/flawiddsouza/Restfox cd Restfox/packages/ui npm i npm run build-web-standalone cd ../web-standalone npm i npm start ``` -------------------------------- ### Start Development Server with npm Source: https://github.com/flawiddsouza/restfox/blob/main/docs/README.md Starts the development server for Restfox, enabling hot-reloading and other development-specific features. This command is typically used during the development phase. ```bash npm run dev ``` -------------------------------- ### Install Restfox using Scoop on Windows Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Installs Restfox on Windows using the Scoop package manager. It first adds the 'extras' bucket and then installs Restfox. ```bash scoop bucket add extras scoop install restfox ``` -------------------------------- ### Docker Compose for Restfox Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts Restfox using Docker Compose in detached mode. This is a basic setup and assumes a docker-compose.yml file is present. ```bash docker-compose up -d ``` -------------------------------- ### Install Project Dependencies with npm Source: https://github.com/flawiddsouza/restfox/blob/main/docs/README.md Installs all the necessary project dependencies using npm. This command should be run in the project's root directory before development or building. ```bash npm install ``` -------------------------------- ### Install Restfox using Snap on Ubuntu Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Installs Restfox on Ubuntu and other snap-supported distributions. This command requires sudo privileges. ```bash sudo snap install restfox ``` -------------------------------- ### Install Restfox using Homebrew on macOS Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Installs Restfox on macOS using the Homebrew package manager. Ensure Homebrew is installed before running this command. ```bash brew install restfox ``` -------------------------------- ### Run Restfox Electron App for Development Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts the Restfox Electron application in development mode. This allows for live reloading and debugging during development. ```bash npm run start ``` -------------------------------- ### Run Restfox Web Standalone with Custom Port Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts the Restfox web-standalone application on a custom port (e.g., 5040) by setting the PORT environment variable before running 'npm start'. ```bash PORT=5040 npm start ``` -------------------------------- ### Make Synchronous HTTP Requests in JavaScript Source: https://context7.com/flawiddsouza/restfox/llms.txt This code demonstrates how to make synchronous HTTP requests from within Restfox plugins using the `fetchSync` API. It covers setting request methods, headers, and bodies, as well as handling responses, including status codes, headers, and JSON data. The example also shows how to use fetched data to set environment variables and modify the current request. ```javascript const timestamp = new Date().getTime() const response = fetchSync('https://api.example.com/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json', 'API-Key': rf.getEnvVar('apiKey') }, body: JSON.stringify({ username: 'testuser', password: 'secure123', grant_type: 'password' }) }) console.log(response.status) // 200 console.log(response.headers.get('content-type')) // application/json const data = response.json() rf.setEnvVar('accessToken', data.access_token) rf.setEnvVar('refreshToken', data.refresh_token) if('request' in rf) { rf.request.setHeader('Authorization', `Bearer ${data.access_token}`) } const userResponse = fetchSync(`https://api.example.com/users/me`, { method: 'GET', headers: { 'Authorization': `Bearer ${data.access_token}` } }) const userData = userResponse.json() rf.setEnvVar('userId', userData.id) rf.setEnvVar('userName', userData.name) ``` -------------------------------- ### Docker Compose for Restfox with Specific Version Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts Restfox using Docker Compose, allowing you to specify the RESTFOX_VERSION environment variable to use a particular version of the application. ```bash RESTFOX_VERSION=0.40.0 docker-compose up -d ``` -------------------------------- ### Run Locally Built Restfox Docker Image Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts a Docker container from a locally built Restfox image. It maps port 4004 and runs the container in detached mode. ```bash docker run -d -p:4004:4004 restfox:xx ``` -------------------------------- ### Upgrade CodeMirror Libraries Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Updates various CodeMirror libraries to their latest versions. This command is useful for getting the newest features and bug fixes for the code editor component. ```bash npm i @codemirror/autocomplete@latest @codemirror/commands@latest @codemirror/lang-javascript@latest @codemirror/lang-json@latest @codemirror/language@latest @codemirror/search@latest @codemirror/state@latest @codemirror/view@latest ``` -------------------------------- ### Run Restfox Docker Container Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts a Restfox Docker container in detached mode, mapping port 4004 from the host to the container. This assumes the Docker image 'flawiddsouza/restfox:0.40.0' is available. ```bash docker run --name Restfox -d -p 4004:4004 flawiddsouza/restfox:0.40.0 ``` -------------------------------- ### Docker Compose for Restfox with Custom Port Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Starts Restfox using Docker Compose, mapping a custom host port (5000) to the container's default port (4004). ```bash docker-compose -p 5000:4004 up -d ``` -------------------------------- ### Making a POST Request with Curl Source: https://github.com/flawiddsouza/restfox/blob/main/packages/ui/test-data/curl-cmd-to-bash/2_output.txt This snippet demonstrates how to execute a POST request to a REST API endpoint using the curl command-line tool. It includes setting custom headers and sending a JSON payload. The payload contains details about the request to be proxied, including the HTTP method, target URI, and a base64 encoded request body. ```shell curl "https://restninja.io/in/proxy" --compressed -X POST -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate, br, zstd' -H 'Origin: https://restninja.io' -H 'DNT: 1' -H 'Sec-GPC: 1' -H 'Connection: keep-alive' -H 'Referer: https://restninja.io/' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-origin' -H 'TE: trailers' --data-raw '{"body":"ewogICAgInByb3AiOiAxMjM0Cn0=","method":"POST","uri":"http://httpbin.org/post","headers":[],"auth":{"_t":"None"}}' ``` -------------------------------- ### Execute Proxy Request with Curl Source: https://github.com/flawiddsouza/restfox/blob/main/packages/ui/test-data/curl-cmd-to-bash/1_input.txt This snippet shows how to use curl to send a POST request to the restninja.io proxy. It includes essential headers for the request, such as 'accept', 'cookie', 'origin', 'referer', and user-agent. The data payload is sent as raw JSON, with a base64 encoded string in the 'body' field. ```shell curl "https://restninja.io/in/proxy" \ -H "accept: */*" \ -H "accept-language: en-GB,en-US;q=0.9,en;q=0.8" \ -H "cookie: _ga_JQXWSK7VEK=GS1.1.1737824556.1.0.1737824556.0.0.0; _ga=GA1.2.1794086968.1737824556; _gid=GA1.2.153220846.1737824556; _gat_gtag_UA_2652919_3=1; sc_is_visitor_unique=rx12865986.1737824557.1C3356BE17DF4F6388E6554EAA9543B9.1.1.1.1.1.1.1.1.1; fpestid=3Imo-s_4xCEdLlYgqpeayp6LlH8U4osgsUAbVTyYQ80YPaSwWEFnWTzrMZxbHMt9_KYqGg; _cc_id=a1405834f5b8d0b9a8df31d04c7d3efa; panoramaId_expiry=1737910958742; twk_idm_key=ObU2AdTki0GszXdOE6vTr; TawkConnectionTime=0; twk_uuid_5ae071e9227d3d7edc24b9dc=%7B%22uuid%22%3A%221.Sww8kNgHf8PApt3jZYdkqIw4OsdAnahoHwG87OOngSx4mxhxCPCkebftcqiMlatJizLVutKb6wyWRBUgYBtWbrIKUszZPFUHiNoocPlgVJRCxRXM38DG0%22%2C%22version%22%3A3%2C%22domain%22%3A%22restninja.io%22%2C%22ts%22%3A1737824561436%7D" \ -H "origin: https://restninja.io" \ -H "priority: u=1, i" \ -H "referer: https://restninja.io/" \ -H "sec-ch-ua: \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"" \ -H "sec-ch-ua-mobile: ?0" \ -H "sec-ch-ua-platform: \"Windows\"" \ -H "sec-fetch-dest: empty" \ -H "sec-fetch-mode: cors" \ -H "sec-fetch-site: same-origin" \ -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36" \ --data-raw "{\"body\":\"eyJ0ZXN0IjogMTIzNH0=\",\"method\":\"POST\",\"uri\":\"http://httpbin.org/post\",\"headers\":[],\"auth\":{\"_t\":\"None\"}}" ``` -------------------------------- ### JavaScript: Restfox Collection Export/Import Format Source: https://context7.com/flawiddsouza/restfox/llms.txt Defines the JSON structure for exporting Restfox collections, including requests, folders, environments, and plugins. It also shows an example of how to import a collection using the store's dispatch method. ```javascript // Collection export format (JSON) const exportData = { exportedFrom: 'Restfox-1.0.0', collection: [ { _id: 'folder-1', _type: 'request_group', name: 'API Endpoints', parentId: null, workspaceId: 'workspace-123', sortOrder: 0, environment: { baseUrl: 'https://api.example.com', apiKey: 'key123' }, environments: [ { name: 'Production', environment: { baseUrl: 'https://api.example.com' } }, { name: 'Staging', environment: { baseUrl: 'https://staging.api.example.com' } } ] }, { _id: 'request-1', _type: 'request', name: 'Get Users', method: 'GET', url: '{{baseUrl}}/users', parentId: 'folder-1', workspaceId: 'workspace-123', parameters: [ { name: 'limit', value: '50' }, { name: 'page', value: '1' } ], headers: [ { name: 'Authorization', value: 'Bearer {{apiKey}}' } ], body: { mimeType: 'No Body' } } ], plugins: [ { _id: 'plugin-1', type: 'request', name: 'Add Timestamp', code: 'rf.request.setHeader("X-Timestamp", Date.now())', workspaceId: 'workspace-123', collectionId: 'request-1', enabled: true } ] } // Import collection await store.dispatch('setCollectionTree', { collectionTree: importedCollections, parentId: 'parent-folder-id', // null for root plugins: importedPlugins }) ``` -------------------------------- ### Manipulate Request Data in Restfox Plugin Context (JavaScript) Source: https://context7.com/flawiddsouza/restfox/llms.txt This example shows how to access and modify various aspects of an API request, including its URL, method, headers, query parameters, path parameters, and body, using the Restfox plugin context API ('rf'). It allows for dynamic manipulation of request data before it's sent. Dependencies include the 'rf' object provided by the Restfox environment and standard browser APIs like 'crypto'. ```javascript if('request' in rf) { const url = rf.request.getURL() console.log('Request URL:', url) const method = rf.request.getMethod() const headers = rf.request.getHeaders() rf.request.setHeader('X-API-Version', 'v2') rf.request.setHeader('X-Request-ID', crypto.randomUUID()) const authHeader = rf.request.getHeader('Authorization') const queryParams = rf.request.getQueryParams() queryParams.push({ name: 'sort', value: 'created_at' }) rf.request.setQueryParams(queryParams) const pathParams = rf.request.getPathParams() pathParams.push({ name: 'id', value: rf.getEnvVar('userId') }) rf.request.setPathParams(pathParams) const body = rf.request.getBody() if(body.mimeType === 'application/json') { const jsonData = JSON.parse(body.text) jsonData.timestamp = new Date().toISOString() jsonData.requestId = crypto.randomUUID() rf.request.setBody({ mimeType: 'application/json', text: JSON.stringify(jsonData) }) } } ``` -------------------------------- ### Proxy POST Request with Curl Source: https://github.com/flawiddsouza/restfox/blob/main/packages/ui/test-data/curl-cmd-to-bash/1_output.txt This snippet shows how to use `curl` to send a proxied POST request through Restfox. It includes essential headers like `accept`, `cookie`, `origin`, `referer`, and user-agent information. The `data-raw` parameter specifies the request method, URI, and an empty headers array for the proxied request. ```curl curl "https://restninja.io/in/proxy" \ -H 'accept: */*' \ -H 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \ -H 'cookie: _ga_JQXWSK7VEK=GS1.1.1737824556.1.0.1737824556.0.0.0; _ga=GA1.2.1794086968.1737824556; _gid=GA1.2.153220846.1737824556; _gat_gtag_UA_2652919_3=1; sc_is_visitor_unique=rx12865986.1737824557.1C3356BE17DF4F6388E6554EAA9543B9.1.1.1.1.1.1.1.1.1; fpestid=3Imo-s_4xCEdLlYgqpeayp6LlH8U4osgsUAbVTyYQ80YPaSwWEFnWTzrMZxbHMt9_KYqGg; _cc_id=a1405834f5b8d0b9a8df31d04c7d3efa; panoramaId_expiry=1737910958742; twk_idm_key=ObU2AdTki0GszXdOE6vTr; TawkConnectionTime=0; twk_uuid_5ae071e9227d3d7edc24b9dc=%7B%22uuid%22%3A%221.Sww8kNgHf8PApt3jZYdkqIw4OsdAnahoHwG87OOngSx4mxhxCPCkebftcqiMlatJizLVutKb6wyWRBUgYBtWbrIKUszZPFUHiNoocPlgVJRCxRXM38DG0%22%2C%22version%22%3A3%2C%22domain%22%3A%22restninja.io%22%2C%22ts%22%3A1737824561436%7D' \ -H 'origin: https://restninja.io' \ -H 'priority: u=1, i' \ -H 'referer: https://restninja.io/' \ -H 'sec-ch-ua: "Chromium";v="125", "Not.A/Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "Windows"' \ -H 'sec-fetch-dest: empty' \ -H 'sec-fetch-mode: cors' \ -H 'sec-fetch-site: same-origin' \ -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36' \ --data-raw '{"body":"eyJ0ZXN0IjogMTIzNH0=","method":"POST","uri":"http://httpbin.org/post","headers":[],"auth":{"_t":"None"}}' ``` -------------------------------- ### cURL POST Request to Restfox API Proxy Source: https://github.com/flawiddsouza/restfox/blob/main/packages/ui/test-data/curl-cmd-to-bash/2_input.txt This snippet shows how to use cURL to send a POST request to the Restfox API proxy. It includes common headers for browser-like requests and a base64 encoded JSON payload. The proxy forwards this request to a specified URI. ```shell curl "https://restninja.io/in/proxy" --compressed -X POST -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" -H "Accept-Encoding: gzip, deflate, br, zstd" -H "Origin: https://restninja.io" -H "DNT: 1" -H "Sec-GPC: 1" -H "Connection: keep-alive" -H "Referer: https://restninja.io/" -H "Sec-Fetch-Dest: empty" -H "Sec-Fetch-Mode: cors" -H "Sec-Fetch-Site: same-origin" -H "TE: trailers" --data-raw "{ \"body\": \"ewogICAgInByb3AiOiAxMjM0Cn0=\", \"method\": \"POST\", \"uri\": \"http://httpbin.org/post\", \"headers\":^[^], \"auth\": { \"_t\": \"None\" }}" ``` -------------------------------- ### Plugin System: Request and Response Scripting in Restfox Source: https://context7.com/flawiddsouza/restfox/llms.txt This snippet demonstrates how to create and execute custom plugins within Restfox's sandboxed QuickJS environment. It covers modifying request headers, body, and query parameters, as well as processing response data to set environment variables and perform assertions. ```javascript // Request Plugin - Modify request before sending if('request' in rf) { // Get and modify request headers rf.request.setHeader('Authorization', 'Bearer ' + rf.getEnvVar('token')) // Modify request body const body = rf.request.getBody() rf.request.setBody({ mimeType: 'application/json', text: JSON.stringify({ timestamp: new Date().getTime(), data: body }) }) // Add query parameters const queryParams = rf.request.getQueryParams() queryParams.push({ name: 'api_key', value: rf.getEnvVar('apiKey') }) rf.request.setQueryParams(queryParams) } // Response Plugin - Process response data if('response' in rf) { const responseBody = rf.response.getBodyJSON() // Set environment variables from response rf.setEnvVar('authToken', responseBody.token) rf.setEnvVar('userId', responseBody.user.id) // Parent environment variable (folder level) rf.setParentEnvVar('sharedToken', responseBody.token) // Test assertions test('Status code is 200', () => { expect(rf.response.getStatusCode()).to.equal(200) }) test('Response has required fields', () => { expect(responseBody).to.have.property('token') expect(responseBody.user).to.have.property('id') }) } ``` -------------------------------- ### Build Restfox UI for Desktop Distribution Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Compiles the Restfox UI specifically for desktop application distribution. ```bash npm run build-desktop ``` -------------------------------- ### Build Project for Production with npm Source: https://github.com/flawiddsouza/restfox/blob/main/docs/README.md Builds the Restfox project for production deployment. This command optimizes the code and assets for a production environment. ```bash npm run build ``` -------------------------------- ### Distribute Restfox Electron App Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Builds distributable packages for the Restfox Electron application. This command prepares the application for release. ```bash npm run make ``` -------------------------------- ### Manage Restfox Workspaces and Collections in JavaScript Source: https://context7.com/flawiddsouza/restfox/llms.txt This snippet demonstrates how to create, organize, duplicate, and delete workspaces and collections within Restfox. It supports both database-backed (indexeddb) and file-based workspaces. Dependencies include the 'store' object provided by the Restfox environment. ```javascript const workspaceId = await store.dispatch('createWorkspace', { name: 'Production API', _type: 'indexeddb', // or 'file' for file-based location: null, // path for file-based workspaces setAsActive: true }) await store.dispatch('createCollectionItem', { type: 'request_group', name: 'User Management', parentId: null // null for root level }) await store.dispatch('createCollectionItem', { type: 'request', name: 'Create User', method: 'POST', url: '{{baseUrl}}/api/users', parentId: 'folder-id', body: { mimeType: 'application/json', text: JSON.stringify({ name: 'John', email: 'john@example.com' }) }, headers: [ { name: 'Content-Type', value: 'application/json' } ] }) await store.dispatch('duplicateWorkspace', { sourceWorkspace: workspace, name: 'Staging Environment', type: 'indexeddb', location: null, includeResponseHistory: true }) await store.dispatch('deleteCollectionItem', collectionItem) await store.dispatch('reorderCollectionItem', { from: { id: 'item-1', parentId: 'folder-1' }, to: { id: 'folder-2', type: 'request_group', cursorPosition: 'bottom' } }) ``` -------------------------------- ### Build Restfox Docker Image Locally Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Builds a Docker image for Restfox locally. This command assumes that the 'packages/ui' directory has been built using 'npm run build-web-standalone'. The '-t' flag tags the image with a name and version. ```bash docker build -t restfox:xx . ``` -------------------------------- ### Build Restfox UI for Web Standalone Distribution Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Compiles the Restfox UI into a standalone web application bundle. ```bash npm run build-web-standalone ``` -------------------------------- ### Make POST Request with cURL Source: https://github.com/flawiddsouza/restfox/blob/main/packages/ui/test-data/curl-cmd-to-bash/3_input.txt This snippet demonstrates how to make a POST request to 'https://httpbin.org/anything' using cURL. It includes various headers to simulate a browser request and sends a JSON payload in the request body. This is useful for testing API endpoints and debugging. ```shell curl "https://httpbin.org/anything" \ -H "authority: httpbin.org" \ -H "accept: */*" \ -H "accept-language: en-US,en;q=0.9" \ -H "cache-control: no-cache" \ -H "content-type: application/json" \ -H "origin: https://restfox.dev" \ -H "pragma: no-cache" \ -H "referer: https://restfox.dev/" \ -H "sec-ch-ua: \"Chromium\";v=\"118\", \"Google Chrome\";v=\"118\", \"Not=A?Brand\";v=\"99\"" \ -H "sec-ch-ua-mobile: ?0" \ -H "sec-ch-ua-platform: \"Windows\"" \ -H "sec-fetch-dest: empty" \ -H "sec-fetch-mode: cors" \ -H "sec-fetch-site: cross-site" \ -H "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" \ --data-raw "{\"test\": \"body\"}" \ --compressed ``` -------------------------------- ### Manage Environment Variables with Scopes in JavaScript Source: https://context7.com/flawiddsouza/restfox/llms.txt This snippet demonstrates how to manage environment variables at different scopes (workspace, folder, request) using the `store.commit` and `store.dispatch` methods. It also shows how to access these variables within the plugin context using `rf.getEnvVar` and `rf.setEnvVar`. Variables support dynamic substitution and inheritance, with later values overriding earlier ones. ```javascript await store.commit('updateWorkspaceEnvironment', { workspaceId: 'workspace-123', environment: { baseUrl: 'https://api.example.com', apiKey: 'sk_test_123', timeout: 5000 } }) await store.commit('updateCollectionItemEnvironment', { collectionId: 'folder-456', environment: { endpoint: '/v1/users', maxResults: 100 } }) const { environment, parentHeaders, parentAuthentication } = await store.dispatch('getEnvironmentForRequest', { collectionItem: request }) rf.setEnvVar('token', 'new-token-value') const token = rf.getEnvVar('token') rf.setParentEnvVar('sharedData', 'value') // Sets at folder level ``` -------------------------------- ### Publish Restfox Electron App Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Publishes the Restfox Electron application, typically to a release platform like GitHub. This command is used after building distributable packages. ```bash npm run publish ``` -------------------------------- ### Upgrade Electron and Forge Dependencies Source: https://github.com/flawiddsouza/restfox/blob/main/README.md Updates Electron and related Electron Forge packages to their latest versions. This command is essential for maintaining the desktop application framework. ```bash npm install --save-dev electron@latest @electron-forge/cli@latest @electron-forge/maker-deb@latest @electron-forge/maker-rpm@latest @electron-forge/maker-squirrel@latest @electron-forge/maker-zip@latest @electron-forge/publisher-github@latest electron-builder@latest ``` -------------------------------- ### HTTP Request Execution in Restfox Source: https://context7.com/flawiddsouza/restfox/llms.txt This snippet illustrates the process of sending HTTP requests within Restfox, including creating new requests in collections, sending requests with environment variable resolution, and the underlying request handling logic. It details the structure of a request response object. ```javascript // From store.ts - sendRequest action // Create a new request in a collection await store.dispatch('createCollectionItem', { type: 'request', name: 'Get User Profile', method: 'GET', url: '{{baseUrl}}/api/users/{{userId}}', parentId: 'collection-folder-id', headers: [ { name: 'Authorization', value: 'Bearer {{token}}' }, { name: 'Content-Type', value: 'application/json' } ] }) // Send request with environment resolution await store.dispatch('sendRequest', activeTab) // Request handler (packages/electron/src/request.js) // Handles SSL verification, DNS lookup, FormData, and file uploads const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token123' }, body: JSON.stringify({ username: 'test', password: 'pass' }), signal: abortController.signal, dispatcher: getAgentForRequest(urlParsed, disableSSLVerification) }) // Response includes status, headers, body, and timing // { // status: 200, // statusText: 'OK', // headers: [['content-type', 'application/json']], // buffer: ArrayBuffer, // timeTaken: 245, // headTimeTaken: 120, // bodyTimeTaken: 125 // } ``` -------------------------------- ### Make Synchronous POST Request with FetchSync in JavaScript Source: https://github.com/flawiddsouza/restfox/blob/main/docs/plugins/making-http-requests.md This snippet demonstrates how to make a synchronous POST request using `fetchSync` in Restfox. It includes setting a timestamp, defining request headers and body, and logging various parts of the response such as status, headers, and content as text or JSON. Dependencies include the built-in `fetchSync` function. ```javascript const timestamp = new Date().getTime() console.log({ timestamp }) // { timestamp: 1713605897068 } const response = fetchSync(`https://httpbin.org/post?param=${timestamp}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'test', password: 'test123' }) }) console.log(response.status) // 200 console.log([...response.headers.entries()]) // [ // [ // "content-length", // "1088" // ], // [ // "content-type", // "application/json" // ] // ] console.log(response.headers.get('content-length')) // 1088 console.log(response.text()) // response as text console.log(response.json()) // response as parsed json // { // "args": { // "param": "1713605897068" // }, // "data": "{\"username\":\"test\",\"password\":\"test123\"}", // "files": {}, // "form": {}, // "headers": { // "Accept": "*/*", // "Accept-Encoding": "gzip, deflate, br, zstd", // "Accept-Language": "en-US,en;q=0.9", // "Content-Length": "40", // "Content-Type": "application/json", // "Host": "httpbin.org", // }, // "json": { // "password": "test123", // "username": "test" // }, // "url": "https://httpbin.org/post?param=1713605897068" // } ``` -------------------------------- ### Tauri Fetch Polyfill Implementation in JavaScript Source: https://github.com/flawiddsouza/restfox/blob/main/packages/tauri/README.md This JavaScript code polyfills the `fetch` function for use within Tauri applications. It intercepts fetch requests and utilizes Tauri's native `__TAURI__.http.fetch` API for network operations. It handles request bodies, methods, and converts URLSearchParams to strings. The polyfill returns a standard `Response` object. ```javascript export async function fetch(input, init) { const fetch = window.__TAURI__.http.fetch const params = { ...init, body: { type: 'Text', payload: init.body } }; if(params.body.payload instanceof URLSearchParams) { params.body.payload = params.body.payload.toString() } if(init.method === 'GET' || 'body' in init === false || init.body === null) { delete params.body } const res = await fetch(input.toString(), params) return new Response(JSON.stringify(res.data), res) } ``` -------------------------------- ### Test API Responses with Chai Assertions in JavaScript Source: https://context7.com/flawiddsouza/restfox/llms.txt This snippet illustrates how to write automated test scripts within Restfox plugins to validate API responses using Chai assertions. It shows how to access response details like body, status code, and headers, and then use various assertion methods (e.g., `expect`, `assert`) to check for expected values, structures, and formats. These tests execute after a response is received and their results are displayed in the UI. ```javascript if('response' in rf) { const response = rf.response.getBodyJSON() const statusCode = rf.response.getStatusCode() const responseTime = rf.response.getResponseTime() test('Response status is 200', () => { expect(statusCode).to.equal(200) }) test('Response time is acceptable', () => { expect(responseTime).to.be.below(1000) }) test('Response has required structure', () => { expect(response).to.have.property('data') expect(response.data).to.be.an('array') expect(response.data).to.have.length.above(0) }) test('User object has valid fields', () => { const user = response.data[0] expect(user).to.have.property('id') expect(user).to.have.property('email') expect(user.email).to.match(/^[w-.]+@([w-]+.)+[w-]{2,4}$/) }) test('Response headers are correct', () => { const contentType = rf.response.getHeader('content-type') expect(contentType).to.include('application/json') }) test('Nested data validation', () => { expect(response.data[0].profile).to.have.property('name') assert.isString(response.data[0].profile.name) assert.isNotEmpty(response.data[0].profile.name) }) } ``` -------------------------------- ### Encrypt and Decrypt Data with CryptoJS AES Source: https://github.com/flawiddsouza/restfox/blob/main/docs/plugins/using-crypto-js.md This snippet shows how to import CryptoJS via esm.sh and use its AES capabilities to encrypt a string and then decrypt it back. It requires the CryptoJS library and a secret key for both operations. The output is the original decrypted string. ```javascript import CryptoJS from 'https://esm.sh/crypto-js@latest?target=es2020' var data = 'my string' const secretKey = 'secret key 123' // Encrypt var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString() // Decrypt var bytes = CryptoJS.AES.decrypt(ciphertext, secretKey) var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)) console.log(decryptedData) // output: my string ``` -------------------------------- ### GZIP Compress and Decompress Text in Restfox (JavaScript) Source: https://github.com/flawiddsouza/restfox/blob/main/docs/plugins/gzip-compressing-&-decompressing-text.md Compresses a string to a base64 encoded GZIP string and decompresses a base64 encoded GZIP string back to its original text. Requires the 'pako' library. It takes string input and outputs base64 encoded strings or decompressed strings. ```javascript import pako from 'https://unpkg.com/pako@2.1.0/dist/pako.esm.mjs?module' // compressing a string to a base64 gzipped string const buffer = rf.arrayBuffer.fromString('My Gzipped Text') const compressedBuffer = pako.deflate(buffer) const compressedText = rf.base64.fromUint8Array(compressedBuffer) console.log(compressedText) // output: eJzzrVQISa0oAQAJewKM // decompressing a base64 gzipped string const buffer2 = rf.base64.toUint8Array(compressedText) const decompressedGzip = pako.inflate(buffer2) const uncompressedText = rf.arrayBuffer.toString(decompressedGzip) console.log(uncompressedText) // output: My Gzipped Text ``` -------------------------------- ### Parse Response and Set Environment Variable (JavaScript) Source: https://github.com/flawiddsouza/restfox/blob/main/docs/plugins/setting-environment-variables-using-response-data.md This plugin parses the response body as JSON and sets an environment variable named 'MyAccessToken' with the value from the 'accessToken' field in the response. It checks if 'response' exists in the context before executing. ```javascript function handleResponse() { const response = context.response.getBodyText() const responseData = JSON.parse(response) context.response.setEnvironmentVariable('MyAccessToken', responseData.accessToken) } if('response' in context) { handleResponse() } ``` -------------------------------- ### JavaScript API Response Testing Plugin Source: https://github.com/flawiddsouza/restfox/blob/main/docs/plugins/testing-response-data.md This JavaScript code defines a function to handle API responses, parse the JSON body, and perform assertions on its properties. It checks for the existence of 'form' and 'args' properties, and validates the content of the 'form' property. The script runs only if a 'response' object is available in the context. ```javascript function handleResponse() { const response = JSON.parse(context.response.getBodyText()) test('check if response has property form and has a key with value 1', () => { expect(response).to.have.property('form') expect(response.form).to.eql({ "key": "1" }) }) test('check if response has property args', () => { expect(response).to.have.property('args') }) } if('response' in context) { handleResponse() } ``` -------------------------------- ### Process HTTP Response Data with Restfox Plugin API Source: https://context7.com/flawiddsouza/restfox/llms.txt Access and process various aspects of an HTTP response, including status codes, headers, body content (as buffer, text, or JSON), and request timing. This API allows for response modification, data extraction for environment variables, and handling binary data. Dependencies include the 'rf' object provided by the Restfox context. ```javascript // Complete response processing example if('response' in rf) { // Status information const status = rf.response.getStatusCode() // 200, 404, 500, etc. const responseTime = rf.response.getResponseTime() // milliseconds // Headers const headers = rf.response.getHeaders() // [['content-type', 'application/json'], ['x-rate-limit', '100']] const contentType = rf.response.getHeader('content-type') const rateLimit = rf.response.getHeader('x-rate-limit') // Set custom response headers (for display/processing) rf.response.setHeader('X-Processed', 'true') // Body access - multiple formats const bodyBuffer = rf.response.getBody() // ArrayBuffer const bodyText = rf.response.getBodyText() // String const bodyJSON = rf.response.getBodyJSON() // Parsed JSON object // Modify response body if(bodyJSON) { bodyJSON.processedAt = new Date().toISOString() bodyJSON.cached = false rf.response.setBodyText(JSON.stringify(bodyJSON, null, 2)) } // URL that was requested const url = rf.response.getURL() // Extract and store tokens if(status === 200 && bodyJSON.token) { rf.setEnvVar('authToken', bodyJSON.token) rf.setEnvVar('tokenExpiry', bodyJSON.expiresAt) } // Handle pagination if(bodyJSON.nextPage) { rf.setEnvVar('nextPageUrl', bodyJSON.nextPage) } // Binary/Buffer operations const bufferString = rf.arrayBuffer.toString(bodyBuffer) const stringBuffer = rf.arrayBuffer.fromString('Hello World') // Base64 operations const base64Data = rf.base64.fromUint8Array(new Uint8Array(bodyBuffer)) const uint8Data = rf.base64.toUint8Array(base64Data) } ``` -------------------------------- ### Manage Response History and Collections with Restfox Store API Source: https://context7.com/flawiddsouza/restfox/llms.txt Utilize the Restfox store API to manage the history of HTTP responses. This includes automatically storing responses, clearing history, renaming responses, deleting specific responses, and accessing the history array. Responses are stored with details like status, headers, buffer, URL, and timing. This functionality relies on the `store` object and dispatch/commit methods. ```javascript // Save response to history (automatic on request send) await store.dispatch('saveResponse', { workspaceId: 'workspace-123', collectionId: 'request-456', response: { _id: nanoid(), status: 200, statusText: 'OK', headers: [['content-type', 'application/json']], buffer: responseBuffer, url: 'https://api.example.com/users', timeTaken: 234, name: 'Custom Response Name', // optional createdAt: new Date().getTime() } }) // Response history is automatically loaded per tab // Stored in state.responses[tabId] array // Limited to DEFAULT_LIMITS.RESPONSE_HISTORY entries // Clear all response history for a request await store.commit('clearResponseHistory') // Rename current response await store.commit('renameCurrentlyActiveResponse', 'Success Case - All Users') // Delete specific response await store.commit('deleteCurrentlyActiveResponse') // Access response history const responses = store.state.responses[activeTabId] // Array of responses sorted by most recent first // Each response has: _id, status, headers, buffer, timeTaken, createdAt // Switch between responses in history store.state.requestResponses[tabId] = responses[2] // View 3rd response ``` -------------------------------- ### Decode JWT Token using JavaScript in Restfox Source: https://github.com/flawiddsouza/restfox/blob/main/docs/plugins/decoding-a-jwt-token.md This snippet demonstrates how to decode a JWT token using the 'jsonwebtoken' library in a Restfox plugin or script. It requires the 'jsonwebtoken' library to be imported and takes the JWT token and a secret key as input. The output is the decoded JWT payload. ```javascript import jsonwebtoken from 'https://esm.sh/jsonwebtoken@9.0.2' const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' const secretKey = 'your-256-bit-secret' console.log(jsonwebtoken.decode(jwtToken, secretKey)) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.