UNPKG

discard-api

Version:

Universal SDK for Discard API - Supporting CJS, ESM, TypeScript, and Browser

1,283 lines (966 loc) β€’ 48 kB
<h1 align="center">Discard Rest APIs</h1> <h2 align="center">TypeScript/JavaScript SDK</h2> <p align="center"> <img src="https://img.shields.io/npm/v/discard-api" alt="NPM Version"> <img src="https://img.shields.io/badge/Made%20with-%E2%9D%A4-red" alt="Made with Love"> <img src="https://img.shields.io/badge/Open%20Source-%F0%9F%8C%90-purple" alt="Open Source"> <img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="MIT"> <img src="https://img.shields.io/badge/TypeScript-Ready-blue.svg" alt="TypeScript"> <img src="https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg" alt="Node.js"> </p> <p align="center"> A hub of RESTful APIs for developers, providing 500+ powerful endpoints across multiple categories.<br> From downloaders and AI tools to image processing, games, and converters - everything you need to elevate your applications to new heights. </p> Explore our complete catalog and documentation at [discardapi.dpdns.org](https://discardapi.dpdns.org) ## Getting Started with Discard Rest APIs **Welcome to Discard Rest APIs, your one-stop solution for seamless API integrations! Our extensive collection of APIs is designed for developers building apps, businesses enhancing services, or tech enthusiasts experimenting with new ideas.** **Step 1: Sign Up & Get Your API Key** [Signup](https://discardapi.dpdns.org/auth) - Create an account to access our API dashboard. Signing up is quick and easy, providing instant access to hundreds of powerful APIs. **Step 2: Choose an API** [Endpoints](https://discardapi.dpdns.org/) - Browse our comprehensive API library and select the API that fits your needs. Each API includes detailed documentation with endpoints, parameters, and response formats. **Step 3: Make Your First API Call** - With your API key in hand, you're ready to start! All our APIs follow REST principles and are designed for simple, intuitive integration. **Step 4: Some Features Are Premium Only πŸ“Š** - For extensive usage and advanced features, upgrade to a PRO or VIP plan offering higher limits, faster response times, and premium feature access. --- A comprehensive JavaScript and TypeScript SDK for the Discard API, providing seamless access to over 500 API endpoints across multiple categories including artificial intelligence, social media downloads, image processing, fake data generation, and much more. The SDK offers universal compatibility across Node.js CommonJS and ES Modules, TypeScript projects, and browser environments through CDN integration. ## Overview The Discard API SDK provides a clean and intuitive interface for interacting with the Discard API service. Built with modern JavaScript and TypeScript, this SDK eliminates the complexity of manual HTTP requests and parameter handling while providing full type safety for TypeScript users. Whether you are building a Node.js application, a browser-based tool, or a TypeScript project, this SDK adapts seamlessly to your environment. The SDK includes over 200 predefined methods covering all major API categories, automatic API key injection, intelligent request handling for both JSON and FormData payloads, configurable response modes, comprehensive error handling with timeout support, and zero runtime dependencies for minimal bundle size. ## Installation The SDK can be installed using any modern JavaScript package manager. For npm users, execute `npm install discard-api` in your project directory. Yarn users should run `yarn add discard-api`, while pnpm users can install with `pnpm add discard-api`. For browser environments, the SDK is available through multiple CDN providers. The unpkg CDN can be accessed at `https://unpkg.com/discard-api@latest/dist/browser/global.min.js`, while jsDelivr users can load the SDK from `https://cdn.jsdelivr.net/npm/discard-api@latest/dist/browser/global.min.js`. ```nginx # NPM npm install discard-api # Yarn yarn add discard-api # PNPM pnpm add discard-api # BUN bun add discard-api ``` ## Quick Start Getting started with the Discard API SDK requires only a few lines of code. For Node.js CommonJS projects, begin by requiring the SDK with `const DiscardAPI = require('discard-api')`, then initialize a new instance by passing your API key in the configuration object. The instance provides immediate access to all API methods through clean, intuitive method calls. ```javascript const DiscardAPI = require('discard-api'); const api = new DiscardAPI({ apiKey: 'your-api-key-here', fullResponse: false }); async function example() { const shortUrl = await api.shortenClck({ url: 'https://github.com/GlobalTechInfo' }); console.log(shortUrl); const joke = await api.dadJoke(); console.log(joke); const users = await api.fakeUsers({ _quantity: 5, _locale: 'en_US', _gender: 'male' }); console.log(users); } example(); ``` For ES Module projects in Node.js, the SDK can be imported using the standard import syntax. This approach provides the same functionality while adhering to modern JavaScript module standards. ```javascript import DiscardAPI from 'discard-api'; const api = new DiscardAPI({ apiKey: 'your-api-key-here' }); const quote = await api.randomQuote(); console.log(quote); ``` TypeScript projects benefit from full type safety and IntelliSense support. Import both the main class and the configuration interface to ensure compile-time type checking across your entire application. ```typescript import DiscardAPI, { DiscardAPIConfig } from 'discard-api'; const config: DiscardAPIConfig = { apiKey: 'your-api-key-here', fullResponse: false, timeout: 30000 }; const api = new DiscardAPI(config); const result = await api.geminiPro({ text: 'Explain quantum computing' }); console.log(result); ``` Browser integration requires loading the SDK from a CDN and accessing it through the global DiscardAPI object. The SDK automatically detects the browser environment and configures itself accordingly. ```html <!DOCTYPE html> <html> <head> <body> <script src="https://unpkg.com/discard-api/dist/browser/global.min.js"></script> <script> const api = new DiscardAPI.default({ apiKey: 'YOUR_API_KEY' }); api.randomQuote().then(console.log); </script> </body> </html> ``` ## Configuration The SDK accepts several configuration options when initializing a new instance. The API key is the only required parameter and authenticates all requests to the Discard API service. The base URL can be customized if you are using a self-hosted instance of the API, though most users will rely on the default production endpoint. The full response option controls whether the SDK returns only the result data or the complete API response including metadata such as creator information and status flags. This defaults to false for cleaner integration, but can be enabled when you need access to additional response metadata. Request timeout specifies the maximum duration in milliseconds that the SDK will wait for an API response before aborting the request. The default timeout of 30 seconds is suitable for most use cases, but can be adjusted based on your specific requirements or network conditions. ```javascript const api = new DiscardAPI({ apiKey: 'your-api-key-here', // Required baseURL: 'https://discardapi.dpdns.org', // Optional fullResponse: false, // Optional, default: false timeout: 30000 // Optional, default: 30000ms }); ``` ## Response Modes The SDK provides two distinct response modes to accommodate different use cases. In result-only mode, which is the default behavior, API responses are automatically unwrapped to return only the data payload. This mode simplifies integration by eliminating the need to access nested result properties in your code. ```javascript const api = new DiscardAPI({ apiKey: 'your-key', fullResponse: false }); const quote = await api.randomQuote(); console.log(quote); // Returns: "Random quote text here" ``` Full response mode preserves the complete API response structure, including creator attribution, status indicators, and any additional metadata provided by the API. This mode is useful when you need to access response metadata or implement custom error handling based on status fields. ```javascript const api = new DiscardAPI({ apiKey: 'your-key', fullResponse: true }); const response = await api.randomQuote(); console.log(response); // Returns: { creator: "Qasim Ali 🩷", result: "...", status: true } ``` The response mode can be toggled at runtime using the configuration methods, allowing you to switch between modes based on specific use cases within your application. This flexibility enables consistent result handling throughout your codebase while providing access to detailed responses when needed. ```javascript api.setFullResponse(true); const fullResponse = await api.dadJoke(); api.setFullResponse(false); const resultOnly = await api.dadJoke(); ``` ## API Categories and Methods The SDK organizes its methods into logical categories corresponding to the Discard API's service offerings. Each category provides specialized functionality for different use cases, from Islamic content and artificial intelligence to social media downloads and data generation. ### Islamic Content The Islamic category provides access to religious texts and resources. Methods include retrieving complete Quran surahs with both text and audio, searching and accessing hadith collections from major books, obtaining prayer times for any city worldwide, accessing specific Quranic verses with translations, retrieving daily Islamic supplications and remembrances, and searching through an extensive library of Islamic scholarly works. Explore All SDK Supported [**Islamic Features**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L110) ```javascript await api.quranSurah({ surah: 'yaseen' }); await api.hadith({ book: 'sahih-muslim', number: '7' }); await api.prayerTiming({ city: 'Jakarta' }); await api.quran({ surah: '2', ayat: '255' }); await api.dua(); await api.searchBooks(); ``` ### Artificial Intelligence The artificial intelligence category offers access to multiple state-of-the-art language models and image generation systems. Available models include Google's Gemini Pro and Flash for advanced reasoning tasks, Meta's Llama for open-source language processing, Mistral AI for efficient text generation, and Qwen Coder optimized for programming assistance. Image generation capabilities include Flux Schnell for rapid generation, Stable Diffusion for high-quality artistic outputs, and DALL-E for creative image synthesis. Explore All SDK Supported [**AI Features**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L155) ```javascript await api.geminiPro({ text: 'What is artificial intelligence?' }); await api.llamaAI({ text: 'Explain machine learning' }); await api.fluxSchnell({ text: 'A beautiful sunset over mountains' }); await api.stableDiffusion({ text: 'Cyberpunk city at night' }); await api.dallE({ text: 'Abstract art in vibrant colors' }); ``` ### Social Media Downloads The download category enables content retrieval from numerous social media platforms. Supported platforms include Facebook for posts and videos, Instagram for posts, reels, stories, and IGTV content, TikTok videos without watermarks, Twitter media including videos and images, YouTube videos and audio in multiple quality options, Pinterest images and videos, Snapchat spotlight content, Reddit posts and media, LinkedIn videos, and many other platforms. Explore All SDK Supported [**Download Features**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L632) ```javascript await api.dlFacebook({ url: 'https://facebook.com/post-url' }); await api.dlInstagram({ url: 'https://instagram.com/p/...' }); await api.dlTikTok({ url: 'https://tiktok.com/@user/video/...' }); await api.dlTwitter({ url: 'https://twitter.com/user/status/...' }); await api.dlYouTube({ url: 'https://youtube.com/watch?v=...', format: 'mp3' }); ``` ### URL Shortening The URL shortening category provides access to multiple URL shortening services. Each service offers unique features and domain options, allowing you to choose the most appropriate service for your needs. Services include is.gd, TinyCC, Clck.ru, TinyURL, Bitly, and several others. The category also includes URL expansion functionality to retrieve original URLs from shortened links. Explore All SDK Supported [**Shortner Features**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L433) ```javascript await api.shortenClck({ url: 'https://github.com/GlobalTechInfo' }); await api.shortenTiny({ url: 'https://nodejs.org' }); await api.shortenBitly({ url: 'https://www.npmjs.com' }); await api.unshort({ url: 'https://clck.ru/3NeLPL' }); ``` ### Image Generation and Processing The image maker category provides extensive tools for creating and manipulating images. Capabilities include QR code generation with customizable size, color, and logo options, text-to-image conversion with multiple styles, barcode generation in various formats including Code128, EAN-13, and QR codes, avatar creation from initials or text, emoji manipulation and artistic effects, carbon code snippet images for documentation, and welcome card generation for communities. Explore All SDK Supported [**Image Makers**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L797) ```javascript await api.qrCode({ text: 'https://example.com' }); await api.qrTag({ text: 'Hello', size: '300x300', color: '255-0-0', logo: 'https://logo-url.png' }); await api.textToPic({ text: 'Discard API' }); await api.textAvatar({ text: 'QA', shape: 'rounded' }); await api.carbonImage({ code: 'const hello = "world";', bg: '#1F816D' }); ``` ### Fake Data Generation The faker category generates realistic synthetic data for testing and development purposes. Available data types include complete user profiles with names, emails, addresses, and demographic information, physical addresses with international support, text content of various lengths, person records with customizable attributes, book information including titles and ISBNs, random images in specified dimensions, credit card information for payment testing, company profiles with business details, geographic location data, and product catalogs with pricing. Explore All SDK Supported [**Faker Features**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L1154) ```javascript await api.fakeUser(); await api.fakeUsers({ _quantity: 10, _locale: 'en_US', _gender: 'male', _seed: 1234 }); await api.fakeAddresses({ _quantity: 5, _country_code: 'US' }); await api.fakeCompanies({ _quantity: 3 }); await api.fakeProducts({ _quantity: 20, _price_min: '10', _price_max: '1000' }); ``` ### Entertainment and Humor The jokes and quotes categories provide access to vast collections of humor and wisdom. Joke categories include dad jokes, programming humor, knock-knock jokes, general jokes, dark humor, seasonal jokes, and jokes organized by themes such as animals, career, food, history, money, movies, music, science, sports, and travel. Quote categories encompass motivational quotes, Islamic wisdom, stoic philosophy, breaking bad quotes, Buddha teachings, Lucifer series quotes, stranger things quotes, pickup lines, random quotes from famous authors, tech tips, coding advice, fun facts, and life hacks. ```javascript await api.dadJoke(); await api.programmingJoke(); await api.randomQuote(); await api.motivQuote(); await api.islamicQuote(); await api.techTip(); await api.funFact(); ``` ### Music Services The music category integrates with major music platforms for search and download capabilities. Spotify integration enables track searching and downloading, SoundCloud support provides access to independent music, lyrics retrieval works for most popular songs, ringtone libraries offer notification and alert sounds, Deezer integration supports track previews and information, and MusicBrainz provides comprehensive music metadata. Explore All SDK Supported [**Music Features**](https://github.com/GlobalTechInfo/discard-api/blob/ee995f9f02f1c1143f44b64abc88c370fe880e9e/src/index.ts#L894) ```javascript await api.searchSpotify({ query: 'never gonna give you up' }); await api.downloadSpotify({ url: 'https://open.spotify.com/track/...' }); await api.lyrics({ song: 'bohemian rhapsody' }); await api.searchSoundCloud({ query: 'electronic music' }); ``` ### Random Images The images category provides access to curated image collections across numerous themes. Available categories include couple photos, food images covering pizza, burgers, dosa, pasta, and biryani, Islamic imagery, technology and programming visuals, gaming graphics, mountain landscapes, famous athletes including Messi and Ronaldo, animal photos featuring cats, dogs, and foxes, coffee imagery, and AI-generated faces of people who do not exist. ```javascript await api.catImage(); await api.dogImage(); await api.programmingImage(); await api.islamicImage(); await api.coffeeImage(); ``` ### Facts and Trivia The facts category delivers interesting information organized by various dimensions. Date facts provide historical events and notable occurrences for specific dates, year facts cover significant events from any year in history, math facts reveal interesting properties of numbers, trivia provides random knowledge across diverse topics, and useless facts offer entertaining but impractical information. ```javascript await api.dateFact({ month: 7, day: 5 }); await api.yearFact({ year: 2024 }); await api.mathFact({ number: 42 }); await api.triviaFact({ number: 100 }); await api.uselessFact(); ``` ### Information ```javascript await api.infoIMDb({ query: 'Game of thrones' }); await api.infoTMDb({ query: 'Game of thrones' }); await api.infoIP({ ip: '8.8.8.8' }); await api.infoUniversity({ country: 'Pakistan' }); await api.infoTrends({ country: 'Pakistan' }); await api.infoGithubUser({username: 'GlobalTechInfo' }); await api.infoGithubRepo({username: 'GlobalTechInfo', repo: 'discard-api' }); await api.infoWeather({ city: 'Lahore' }); await api.infoWikipedia({ query: 'something' }); ``` ### Tools and Misc ```javascript await api.toolsDictionary({ word: 'How' }); await api.toolsScreenshot({ url: 'https://somelink...' }); await api.toolsTranslate({ text: 'some text', to: 'ur' }); await api.toolsTextStats({ text: 'some text' }); await api.toolsUnitConvert({ from: 'c' to: 'f', value: 20 }); await api.toolsStyleText({ text: 'How' }); await api.toolsHandwriting({ text: 'Write This' }); await api.toolsPing({ url: 'https://some....' }); ``` ### News And Articles ```javascript await api.AljazeeraEnglish(); await api.AlJazeeraArticle({ url: 'article url' }); await api.CNNNews(); await api.CNNArticle(params: { url: 'string' }); await api.SkyNews(); await api.SkyArticle(params: { url: 'string' }); await api.SkySports(); await api.SportsArticle(params: { url: 'string' }); await api.GeoNews(); await api.GeoArticle({ url: 'string' }); await api.ExpressNews(); await api.ExpressArticle({ url: 'https://some....' }); ``` ### Search And Hot ```javascript await api.searchGoogle({ query: 'string' }); await api.searchBing({ query: 'string' }); await api.searchYoutube({ query: 'string' }); await api.searchTracks({ query: 'string' }); await api.searchGifs({ query: 'string' }); await api.searchStickers({ query: 'string' }); await api.searchWattpad({ query: 'string' }); await api.searchItunes({ query: 'string' }); ``` ### Encoding and Decoding The codec category provides comprehensive encoding and decoding utilities. Supported formats include Base64, Base32, Base16, Base36, Base45, Base58, Base62, Base85, and Base91 encoding schemes, binary conversion between text and binary representations, and Brainfuck code generation and interpretation for esoteric programming. ```javascript await api.base64({ mode: 'encode', data: 'Hello World' }); await api.base64({ mode: 'decode', data: 'SGVsbG8gV29ybGQ=' }); await api.binary({ mode: 'encode', data: 'Test' }); await api.brainfuck({ text: 'Hello' }); ``` ## File Upload Support Several API endpoints support file uploads for processing operations. The SDK automatically handles file uploads using FormData when appropriate, supporting operations such as image to Base64 conversion, emoji mosaic generation from uploaded images, and other file-based transformations. ```javascript // Browser environment const fileInput = document.getElementById('fileInput'); const formData = new FormData(); formData.append('file', fileInput.files[0]); await api.img2Base64(formData); // Node.js environment with form-data package const FormData = require('form-data'); const fs = require('fs'); const formData = new FormData(); formData.append('file', fs.createReadStream('image.jpg')); await api.img2Base64(formData); ``` ## Error Handling The SDK implements comprehensive error handling to help you build robust applications. All methods return promises that reject with descriptive error messages when requests fail. Network timeouts are automatically detected and reported, HTTP errors include status codes for debugging, and API errors pass through server messages when available. ```javascript try { const result = await api.dlTikTok({ url: 'invalid-url' }); console.log(result); } catch (error) { if (error.message === 'Request timeout') { console.error('The request took too long to complete'); } else if (error.message.includes('HTTP error')) { console.error('The API returned an error status'); } else { console.error('An unexpected error occurred:', error.message); } } ``` ## Examples In Other Programming Languages <details> <summary><b>Click to expand</b></summary> ### Request Format ```http GET https://discardapi.dpdns.org/api/endpoint?apikey=YOUR_KEY ``` **Request Parameters** | Name | Type | Required | Description | | ------ | ------ | -------- | ----------------------------------- | | apikey | string | βœ… | Your API key | ```json { "status": true, "creator": "Qasim Ali 🩷", "result": {"..."} } ``` --- ### πŸ“Œ API Examples --- ### AlJazeera Headlines (🟒GET) **Endpoint** ```nginx GET https://discardapi.dpdns.org/api/aljazeera?apikey=YOUR_API_KEY ``` **Request Parameters** | Name | Type | Required | Description | | ------ | ------ | -------- | ----------------------------------- | | apikey | string | βœ… | Your API key | **Response** ```json { "status": true, "creator": "Qasim Ali 🩷", "result": [ { "id": "article-id", "title": "Breaking news headline", "image": "https://www.aljazeera.com/someimage.jpg", "url": "https://www.aljazeera.com/news/2025/09/20/article-id" } ], "timestamp": "2025-09-20 03:04 PM" } ``` ### Full Article (🟒GET) **Endpoint** ```nginx GET https://discardapi.dpdns.org/api/aljazeera/article?apikey=YOUR_API_KEY&url=https://www.aljazeera.com/news/2025/09/20/article-id ``` **Request Parameters** | Name | Type | Required | Description | | ------ | ------ | -------- | ----------------------------------- | | apikey | string | βœ… | Your API key | | url | string | βœ… | Link/Url of the article | **Response** ```json { "status": true, "creator": "Qasim Ali 🩷", "result": { "title": "Breaking news headline", "subhead": "Article subhead", "content": "Full article text...", "image": "https://www.aljazeera.com/someimage.jpg", }, "timestamp": "2025-09-20 03:04 PM" } ``` **cURL** ```nginx curl "https://discardapi.dpdns.org/api/aljazeera?apikey=YOUR_API_KEY" curl "https://discardapi.dpdns.org/api/aljazeera/article?apikey=YOUR_API_KEY&url=https://www.aljazeera.com/news/2025/09/20/article-id" ``` **Python** ```py import requests base = "https://discardapi.dpdns.org/api" res = requests.get(f"{base}/aljazeera", params={"apikey": "YOUR_API_KEY"}) print(res.json()) res = requests.get(f"{base}/aljazeera/article", params={ "apikey": "YOUR_API_KEY", "url": "https://www.aljazeera.com/news/2025/09/20/article-id" }) print(res.json()) ``` **Go** ```go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, _ := http.Get("https://discardapi.dpdns.org/api/aljazeera?apikey=YOUR_API_KEY") body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) resp, _ = http.Get("https://discardapi.dpdns.org/api/aljazeera/article?apikey=YOUR_API_KEY&url=https://www.aljazeera.com/news/2025/09/20/article-id") body, _ = ioutil.ReadAll(resp.Body) fmt.Println(string(body)) } ``` **PHP** ```php <?php $articles = file_get_contents("https://discardapi.dpdns.org/api/aljazeera?apikey=YOUR_API_KEY"); echo $articles; $article = file_get_contents("https://discardapi.dpdns.org/api/aljazeera/article?apikey=YOUR_API_KEY&url=https://www.aljazeera.com/news/2025/09/20/article-id"); echo $article; ?> ``` **Java** ```java import okhttp3.*; public class Main { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://discardapi.dpdns.org/api/aljazeera?apikey=YOUR_API_KEY") .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } Request articleRequest = new Request.Builder() .url("https://discardapi.dpdns.org/api/aljazeera/article?apikey=YOUR_API_KEY&url=https://www.aljazeera.com/news/2025/09/20/article-id") .build(); try (Response response = client.newCall(articleRequest).execute()) { System.out.println(response.body().string()); } } } ``` **Swift** ```swift import Foundation let url = URL(string: "https://discardapi.dpdns.org/api/aljazeera?apikey=YOUR_API_KEY")! let task = URLSession.shared.dataTask(with: url) { data, _, error in if let error = error { print("Error:", error) return } if let data = data, let response = String(data: data, encoding: .utf8) { print("Articles:", response) } } task.resume() let detailURL = URL(string: "https://discardapi.dpdns.org/api/aljazeera/article?apikey=YOUR_API_KEY&url=https://www.aljazeera.com/news/2025/09/20/article-id")! let detailTask = URLSession.shared.dataTask(with: detailURL) { data, _, error in if let error = error { print("Error:", error) return } if let data = data, let response = String(data: data, encoding: .utf8) { print("Article Detail:", response) } } detailTask.resume() ``` --- ### Update Product (🟀PUT) **Endpoint** ```nginx PUT https://discardapi.dpdns.org/api/update/product?id={product_id}&apikey={your_api_key} ``` **Request Parameters** **Query Parameters** | Name | Type | Required | Description | |--------|--------|----------|------------------------| | apikey | string | βœ… | Your API key | | id | int | βœ… | Product ID to update | **Body Parameters (JSON or Form Data)** | Name | Type | Required | Description | |-------------|-----------|----------|---------------------------------| | id | int/string| βœ… | Must match the `id` in query | | title | string | βœ… | Product title | | price | string | βœ… | Product price | | description | string | βœ… | Product description | | category | string | βœ… | Product category | | image | string | βœ… | Product image URL | **Response Format** ```json { "status": true, "creator": "Qasim Ali 🩷", "result": { "id": 1, "title": "Updated Product", "price": "15.99", "description": "Updated description here", "category": "electronics", "image": "https://example.com/image.png" } } ``` **cURL** ```bash curl -X PUT "https://discardapi.dpdns.org/api/update/product?id=1&apikey=your_api_key" \ -H "Content-Type: application/json" \ -d '{ "id": 1, "title": "Updated Product", "price": "15.99", "description": "Updated description here", "category": "electronics", "image": "https://example.com/image.png" }' ``` **Python** ```py import requests url = "https://discardapi.dpdns.org/api/update/product" params = {"id": 1, "apikey": "your_api_key"} data = { "id": 1, "title": "Updated Product", "price": "15.99", "description": "Updated description here", "category": "electronics", "image": "https://example.com/image.png" } res = requests.put(url, params=params, json=data) print(res.json()) ``` **PHP** ```php <?php $url = "https://discardapi.dpdns.org/api/update/product?id=1&apikey=your_api_key"; $data = [ "id" => 1, "title" => "Updated Product", "price" => "15.99", "description" => "Updated description here", "category" => "electronics", "image" => "https://example.com/image.png" ]; $options = [ "http" => [ "method" => "PUT", "header" => "Content-Type: application/json", "content" => json_encode($data) ] ]; $context = stream_context_create($options); $response = file_get_contents($url, false, $context); echo $response; ?> ``` --- --- ### 🎴 Vignette Image (πŸ”΅POST) **Endpoint** ```nginx POST https://discardapi.dpdns.org/api/image/vignette ``` **Request Parameters** | Name | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------------| | apikey | string | βœ… | Your API key | | file | file | βœ… | Image file to process | | intensity | float | ❌ | Vignette intensity (0.1–1.0, default: `0.5`) | | shape | string | ❌ | Shape of vignette β†’ `"circle"` or `"rectangle"` | | color | string | ❌ | Vignette color β†’ `"black"` or HEX code (`#rrggbb`) | **Response** - Success (Image Stream) - Content-Type: image/jpeg (or image/png depending on input) - Response is the processed image. **cURL** ```bash curl -X POST "https://discardapi.dpdns.org/api/image/vignette" \ -F "apikey=your_api_key" \ -F "file=@input.jpg" \ -F "intensity=0.8" \ -F "shape=circle" \ -F "color=#000000" \ --output output.jpg ``` **Python** ```py import requests url = "https://discardapi.dpdns.org/api/image/vignette" files = {"file": open("input.jpg", "rb")} data = { "apikey": "your_api_key", "intensity": "0.8", "shape": "circle", "color": "#000000" } res = requests.post(url, files=files, data=data, stream=True) if res.headers.get("Content-Type", "").startswith("image/"): with open("output.jpg", "wb") as f: for chunk in res.iter_content(1024): f.write(chunk) else: print(res.json()) # error JSON ``` **PHP** ```php <?php $url = "https://discardapi.dpdns.org/api/image/vignette"; $postfields = [ "apikey" => "your_api_key", "file" => new CURLFile("input.jpg"), "intensity" => "0.8", "shape" => "circle", "color" => "#000000" ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); if (strpos($contentType, "image/") === 0) { file_put_contents("output.jpg", $response); } else { echo $response; // JSON error } ?> ``` **Go** ```go package main import ( "fmt" "io" "mime/multipart" "net/http" "os" "strings" ) func main() { url := "https://discardapi.dpdns.org/api/image/vignette" // Create multipart form body := &strings.Builder{} writer := multipart.NewWriter(body) // Add API key and params _ = writer.WriteField("apikey", "your_api_key") _ = writer.WriteField("intensity", "0.8") _ = writer.WriteField("shape", "circle") _ = writer.WriteField("color", "#000000") // Add file file, err := os.Open("input.jpg") if err != nil { panic(err) } defer file.Close() part, err := writer.CreateFormFile("file", "input.jpg") if err != nil { panic(err) } _, _ = io.Copy(part, file) writer.Close() // Send request req, _ := http.NewRequest("POST", url, strings.NewReader(body.String())) req.Header.Set("Content-Type", writer.FormDataContentType()) client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() // Check if response is image contentType := resp.Header.Get("Content-Type") if strings.HasPrefix(contentType, "image/") { out, _ := os.Create("output.jpg") defer out.Close() _, _ = io.Copy(out, resp.Body) fmt.Println("βœ… Saved processed image to output.jpg") } else { // Print JSON error errResp, _ := io.ReadAll(resp.Body) fmt.Println(string(errResp)) } } ``` --- ### πŸ“¦ Catbox File Upload API (πŸ”΅POST) **Endpoint:** ```nginx POST https://discardapi.dpdns.org/api/catbox ``` **Request Parameters** | Name | Type | Required | Description | | ------ | ------ | -------- | ----------------------------------- | | apikey | string | βœ… | Your API key | | file | file | βœ… | File to upload (any type supported) | **Response Format** ```json { "status": true, "creator": "Qasim Ali 🩷", "result": { "url": "https://files.catbox.moe/abcd123.zip" } ``` **cURL** ```bash curl -X POST "https://discardapi.dpdns.org/api/catbox" \ -F "apikey=your_api_key" \ -F "file=@example.zip" ``` **Python** ```py import requests url = "https://discardapi.dpdns.org/api/catbox" files = {"file": open("example.pdf", "rb")} data = {"apikey": "your_api_key"} res = requests.post(url, files=files, data=data) print(res.json()) ``` **PHP** ```php <?php $ch = curl_init("https://discardapi.dpdns.org/api/catbox"); $post = [ "apikey" => "your_api_key", "file" => new CURLFile("example.docx") ]; curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ?> ``` **Go** ```go package main import ( "bytes" "fmt" "io" "mime/multipart" "net/http" "os" ) func main() { file, _ := os.Open("example.mp4") defer file.Close() body := &bytes.Buffer{} writer := multipart.NewWriter(body) writer.WriteField("apikey", "your_api_key") part, _ := writer.CreateFormFile("file", "example.mp4") io.Copy(part, file) writer.Close() req, _ := http.NewRequest("POST", "https://discardapi.dpdns.org/api/catbox", body) req.Header.Set("Content-Type", writer.FormDataContentType()) client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() buf := new(bytes.Buffer) buf.ReadFrom(resp.Body) fmt.Println(buf.String()) } ``` **Java** ```java import okhttp3.*; import java.io.File; import java.io.IOException; public class Upload { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); File file = new File("example.mp3"); RequestBody body = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("apikey", "your_api_key") .addFormDataPart("file", file.getName(), RequestBody.create(file, MediaType.parse("application/octet-stream"))) .build(); Request request = new Request.Builder() .url("https://discardapi.dpdns.org/api/catbox") .post(body) .build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } } ``` **C#** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main() { var client = new HttpClient(); var form = new MultipartFormDataContent(); form.Add(new StringContent("your_api_key"), "apikey"); form.Add(new StreamContent(System.IO.File.OpenRead("example.txt")), "file", "example.txt"); var res = await client.PostAsync("https://discardapi.dpdns.org/api/catbox", form); var response = await res.Content.ReadAsStringAsync(); Console.WriteLine(response); } } ``` **Swift** ```swift import Foundation let url = URL(string: "https://discardapi.dpdns.org/api/catbox")! var request = URLRequest(url: url) request.httpMethod = "POST" let boundary = UUID().uuidString request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") var body = Data() body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"apikey\"\r\n\r\n".data(using: .utf8)!) body.append("your_api_key\r\n".data(using: .utf8)!) let fileURL = URL(fileURLWithPath: "example.mov") let fileData = try Data(contentsOf: fileURL) body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"file\"; filename=\"example.mov\"\r\n".data(using: .utf8)!) body.append("Content-Type: application/octet-stream\r\n\r\n".data(using: .utf8)!) body.append(fileData) body.append("\r\n".data(using: .utf8)!) body.append("--\(boundary)--\r\n".data(using: .utf8)!) request.httpBody = body URLSession.shared.dataTask(with: request) { data, _, _ in if let data = data { print(String(data: data, encoding: .utf8)!) } }.resume() ``` **Kotlin** ```kotlin import okhttp3.* import java.io.File fun main() { val client = OkHttpClient() val file = File("example.apk") val body = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("apikey", "your_api_key") .addFormDataPart("file", file.name, file.asRequestBody("application/octet-stream".toMediaType())) .build() val request = Request.Builder() .url("https://discardapi.dpdns.org/api/catbox") .post(body) .build() client.newCall(request).execute().use { response -> println(response.body?.string()) } } ``` --- ### 🚨 Common Error Codes - ![](https://img.shields.io/badge/401-red) Please provide the apikey or Invalid apikey - ![](https://img.shields.io/badge/403-orange) This endpoint requires Special API key - ![](https://img.shields.io/badge/400-orange) Please provide the (query) e.g url - ![](https://img.shields.io/badge/429-yellow) Rate limit exceeded, please wait until reset ### 🚨 Error Handling Comprehensive error codes with detailed descriptions and resolution steps. All errors include helpful context and suggestions. --- #### πŸ”‘ Authentication Errors - ![](https://img.shields.io/badge/401-red) **notparam** β†’ API key parameter missing ➝ Add `?apikey=YOUR_KEY` to your request - ![](https://img.shields.io/badge/401-orange) **invalidKey** β†’ Invalid API key provided ➝ Check your key or generate a new one - ![](https://img.shields.io/badge/400-orange) **notquery** β†’ Missing required query parameter ➝ Please provide query (e.g. `url`) - ![](https://img.shields.io/badge/403-purple) **notspecial** β†’ Requires premium API key ➝ Upgrade your account for access --- #### ⏳ Rate Limiting & System - ![](https://img.shields.io/badge/429-yellow) **limit** β†’ Rate limit exceeded ➝ Wait for reset or upgrade plan - ![](https://img.shields.io/badge/500-gray) **internal** β†’ Internal server error ➝ Temporary issue, try again later - ![](https://img.shields.io/badge/404-blue) **notfound** β†’ Endpoint or resource not found ➝ Check the URL and parameters --- #### πŸ’‘ Best Practices - βœ… Always check the `status` field before processing results - βœ… Implement exponential backoff for **rate limit** errors - βœ… Log error codes for debugging & monitoring - βœ… Handle network timeouts gracefully ---- </details> ## Testing The SDK includes comprehensive test suites for all supported environments. The CommonJS test suite verifies Node.js compatibility using require syntax. The ES Module test suite confirms modern JavaScript import functionality. The TypeScript test suite validates type safety and interface compliance. The browser test suite checks CDN integration and browser API compatibility. To run the tests, first ensure you have built the SDK distribution files by executing `npm run build` in the project directory. Then update the API key in the relevant test file located in the test directory. Execute the appropriate test command such as `node test/test.cjs` for CommonJS testing or `node test/test.mjs` for ES Module testing. TypeScript tests require compilation with `npx tsx test/test.ts`, while browser tests can be opened directly in any modern web browser by launching the test-browser.html file. ## TypeScript Support The SDK includes comprehensive TypeScript definitions for all methods and interfaces. Type definitions cover the main DiscardAPI class with all 300-plus methods, the DiscardAPIConfig interface for initialization options, and the APIResponse interface for full response mode. Import type definitions alongside the SDK for full IntelliSense support in your TypeScript projects. ```typescript import DiscardAPI, { DiscardAPIConfig, APIResponse } from 'discard-api'; const config: DiscardAPIConfig = { apiKey: 'your-key', fullResponse: true }; const api = new DiscardAPI(config); const response: APIResponse = await api.randomQuote(); ``` ## Browser Compatibility The SDK supports all modern browsers with native fetch API support. This includes Chrome version 42 and higher, Firefox version 39 and higher, Safari version 10.1 and higher, Edge version 14 and higher, and Opera version 29 and higher. For older browser support, include a fetch polyfill before loading the SDK script. ## Node.js Compatibility The SDK requires Node.js version 18.0.0 or higher due to its dependency on the native fetch API. The SDK has been tested and confirmed compatible with Node.js versions 18, 20, 21, 22, 23, and 24. No additional dependencies or polyfills are required for supported Node.js versions. ## Performance Considerations The SDK is designed for optimal performance across all environments. With zero runtime dependencies, the browser bundle remains small at approximately 50KB minified. Request pooling and connection reuse are handled automatically by the underlying fetch implementation. Built-in timeout protection prevents hanging requests from consuming resources. Automatic retry logic is not implemented by default, allowing you to implement custom retry strategies that match your application requirements. ## Rate Limiting The Discard API implements rate limiting to ensure fair usage across all users. Rate limit details and current quotas are available in your Discard API dashboard. The SDK does not implement automatic rate limit handling, so you should implement appropriate throttling mechanisms in your application code. Response headers may include rate limit information that you can access when using full response mode. ## Security Best Practices When deploying applications using this SDK, follow security best practices to protect your API credentials and user data. Never commit API keys to version control systems or expose them in client-side code. Use environment variables to store sensitive configuration in production environments. Implement server-side proxies for browser applications to keep API keys secure. Rotate API keys periodically and immediately if you suspect compromise. Validate and sanitize all user input before passing it to SDK methods. ## Contributing Contributions to the Discard API SDK are welcome and appreciated. To contribute, begin by forking the repository at https://github.com/GlobalTechInfo/discard-api. Create a feature branch for your changes using descriptive naming conventions. Make your modifications while ensuring existing tests continue to pass. Add new tests to cover your changes when applicable. Submit a pull request with a clear description of your improvements. ## License This SDK is released under the MIT License, granting permission to use, copy, modify, merge, publish, distribute, sublicense, and sell copies of the software. The software is provided without warranty of any kind, express or implied. The complete license text is available in the LICENSE file included with the SDK distribution. ## Support and Resources For comprehensive API documentation and endpoint references, visit the official Discard API documentation at https://discardapi.dpdns.org. Report bugs and request features through the GitHub issue tracker at https://github.com/GlobalTechInfo/discard-api/issues. View the complete source code and contribute to development at https://github.com/GlobalTechInfo/discard-api. For general questions and community discussion, join our Discord community or open a GitHub discussion. ## Changelog Version 2.0.0 represents the initial release of the Discard API SDK. This release includes full TypeScript support with comprehensive type definitions, universal module support for CommonJS, ES Modules, and browser environments, over 300 predefined methods covering all major API categories, configurable response format with result-only and full response modes, comprehensive error handling with timeout protection, zero runtime dependencies for minimal bundle size, extensive test coverage across all supported environments, and complete documentation with examples for all methods. ## Author This SDK was created and is maintained by Qasim Ali. Connect with the author on GitHub at https://github.com/GlobalTechInfo or visit the project homepage for updates and announcements. ## Acknowledgments Special thanks to all contributors who have helped improve this SDK through bug reports, feature requests, and code contributions. This SDK builds upon the robust Discard API service, and we appreciate the ongoing development and maintenance of the underlying API infrastructure. The open source community provides invaluable tools and libraries that make projects like this possible. ## Made with ❀️ by Qasim Ali Package Name: discard-api Version: 2.0.0 Repository: https://github.com/GlobalTechInfo/discard-api NPM: https://www.npmjs.com/package/discard-api ## 🎧 Support & Contact Need help or want to upgrade? Our team is here to assist you with integration, troubleshooting, and custom solutions. ### πŸ“ž Contact Methods - ![](https://img.shields.io/badge/Email-blue) **Email Support** β†’ [discardapi@gmail.com](mailto:discardapi@gmail.com?subject=Support&body=Hello%20Team,) - ![](https://img.shields.io/badge/WhatsApp-green) **Live Chat** β†’ [Chat on WhatsApp](https://wa.me/923051391007?text=Hello%20I%20need%20support) - ![](https://img.shields.io/badge/Discord-purple) **Community Support** β†’ [Join our Discord Server](https://discord.gg/YBkzCWqz) - ![](https://img.shields.io/badge/GitHub-black) **Documentation** β†’ [GitHub Examples](https://github.com/GlobalTechInfo/discard-api) --- ### ⏱ Response Times - βœ… **Premium Support** β†’ < 1 hour - πŸ†“ **Free Support** β†’ < 24 hours --- Β© 2025 **Discard API** β€” Built with Go & Fiber