Genuinely useful API one-liners are short, self-contained code snippets that perform a complete task—like fetching JSON, formatting a date, or hashing a string—using a single expression. This article lists several you should try at least once, with explanations of what each does, why it’s useful, and how to adapt it.
What Makes an API One-Liner Useful?
A one-liner is useful when it solves a common problem without needing extra libraries, setup, or boilerplate. The best ones are readable, idiomatic, and often chain built-in methods. They save time during development and are easy to remember. The examples below use JavaScript (Node.js and browser) and Python, as those are the most common environments for quick API experimentation.
Fetch JSON from an API (JavaScript)
In the browser or Node.js (with fetch), getting JSON from an endpoint can be done in one line:
const data = await (await fetch('https://api.example.com/data')).json();
This uses await twice: first to wait for the HTTP response, then to parse the body as JSON. The result is a JavaScript object ready to use. In Node.js, you need version 18 or later for global fetch, or you can use a library like node-fetch. This pattern is the foundation of most API interactions.
Format a Date to ISO String (JavaScript)
Converting a Date object to an ISO 8601 string is a one-liner that’s handy for logging, storing, or sending to APIs:
const iso = new Date().toISOString();
This outputs something like 2025-04-07T14:32:10.123Z. The timezone is always UTC, which is perfect for consistent storage. If you need local time, you can use toLocaleString(), but that includes locale-specific formatting. For most API work, ISO 8601 is the standard.
Parse a URL into Parts (JavaScript)
Extracting the hostname, path, or query parameters from a URL is a common need. The URL constructor makes it a one-liner:
const { hostname, pathname, searchParams } = new URL('https://api.example.com/users?id=42');
Now hostname is api.example.com, pathname is /users, and searchParams is a URLSearchParams object you can query with searchParams.get('id'). This works in browsers and Node.js (v10+). It’s much safer than manual string splitting.
Flatten a Nested Array (JavaScript)
If you have an array of arrays and want a single flat array, use flat():
const flat = [[1,2],[3,4]].flat(); // [1,2,3,4]
You can also specify depth: flat(2) flattens two levels. For deep flattening, use Infinity. This is useful when an API returns nested structures and you need a simple list.
Group Array Items by a Key (JavaScript)
Grouping objects by a property is a frequent task. Using reduce() in one line:
const groups = data.reduce((acc, item) => ((acc[item.category] ??= []).push(item), acc), {});
This creates an object where keys are categories and values are arrays of items. The ??= operator initializes an empty array if the key doesn’t exist. It’s compact but still readable if you understand reduce.
Read a File Line by Line (Python)
Python’s list comprehension makes file reading a one-liner:
lines = [line.strip() for line in open('file.txt')]
This opens the file, reads all lines, strips newline characters, and stores them in a list. It’s a quick way to load configuration or data files. However, it doesn’t close the file explicitly; in a long-running script, use a with block instead, but for a one-off script it’s fine.
Calculate SHA256 Hash (Python)
Hashing a string with SHA256 is a one-liner using the hashlib module:
hash = __import__('hashlib').sha256(b'Hello').hexdigest()
This outputs the hex digest of the hash. You can replace b'Hello' with any bytes. Useful for checksums, API tokens, or verifying data integrity. Remember to encode strings to bytes first.
Encode a String to Base64 (Node.js)
Base64 encoding is common for API authentication or data transfer. In Node.js:
const encoded = Buffer.from('user:pass').toString('base64');
This encodes the string to Base64. To decode, use Buffer.from(encoded, 'base64').toString(). In browsers, you can use btoa() for simple strings, but note it doesn’t handle Unicode well.
Check If an Object Is Empty (JavaScript)
Testing if an object has no keys is a one-liner:
const isEmpty = Object.keys(obj).length === 0;
This works for plain objects. For arrays, you can check arr.length === 0. This is handy when an API returns an empty object and you need to handle it gracefully.
Frequently Asked Questions
Do these one-liners work in all browsers?
Most modern browsers support fetch, URL, and flat. However, older browsers (like IE11) don’t. If you need broad compatibility, use a transpiler like Babel or stick to older syntax. For Node.js, check the version for global fetch (v18+).
How do I handle errors in a one-liner?
One-liners are best for quick scripts. For production, wrap them in try/catch or use .catch(). For example: fetch(url).then(r => r.json()).catch(err => console.error(err)). You can still keep it short but add error handling.
Can I use these in Python too?
Yes, many have Python equivalents. For example, fetching JSON: data = requests.get(url).json() (requires the requests library). For hashing, use hashlib as shown. Python’s syntax often allows similar concise expressions.
Are one-liners always the best choice?
Not always. Readability matters. If a one-liner is too clever, it becomes hard to maintain. Use them when the logic is simple and obvious. For complex operations, a multi-line function is clearer.
Where can I practice these?
You can try them in your browser console (F12) or in Node.js REPL. Many online playgrounds like CodePen or Replit allow quick testing. Start with the fetch example using a public API like JSONPlaceholder.