API Documentation
Integrate Web Formatter's code formatting capabilities into your own applications with our powerful API.
Get started quickly without any authentication requirements. Perfect for personal projects and prototypes.
Fair usage limits to ensure availability for all users. Exceeding limits will result in temporary blocks.
API Overview
Web Formatter provides a RESTful API that allows you to format code programmatically. Our API supports all the same languages and formatting options as our web interface, making it easy to integrate code formatting into your own applications.
Base URL
https://web-formatter.com/api/v2
Format Endpoint
/format
Request Parameters
Parameter | Type | Required | Description |
---|---|---|---|
code | string | Yes | The code to format |
language | string | No | Language identifier (auto-detected if omitted). Supported values: HTML, CSS, JavaScript, PHP, JSON, TypeScript, YAML, SQL, XML, Markdown, Ruby, Python, Java, C#, Go, Rust, Swift, C++, Shell Script, GraphQL, SCSS, LESS, Dart, Kotlin, R, Lua, Haskell, Perl, Assembly |
options | object | No | Formatting options (see below) |
Formatting Options
Option | Type | Default | Description |
---|---|---|---|
indentSize | number | 2 | Number of spaces per indentation level |
useTabs | boolean | false | Use tabs instead of spaces for indentation |
minify | boolean | false | Minify the code instead of formatting it |
Response Format
Field | Type | Description |
---|---|---|
success | boolean | Indicates if the request was successful |
language | string | The detected or specified language |
formattedCode | string | The formatted or minified code |
validation | object | Validation results with valid status and messages |
stats | object | Statistics about the code (size, lines) |
error | string | Error message (only present if success is false) |
Rate Limit Headers
Header | Description |
---|---|
X-RateLimit-Limit | Maximum number of requests allowed per minute |
X-RateLimit-Remaining | Number of requests remaining in the current time window |
X-RateLimit-Reset | Time in seconds until the rate limit resets |
Retry-After | Time in seconds to wait before retrying (only sent when rate limited) |
Error Codes
Status Code | Description |
---|---|
400 | Bad Request - Invalid parameters or missing required fields |
413 | Payload Too Large - Code exceeds the 1MB size limit |
422 | Unprocessable Entity - Code could not be formatted |
429 | Too Many Requests - Rate limit exceeded |
500 | Internal Server Error - Something went wrong on our end |
Code Examples
Here are examples of how to use the Web Formatter API in various programming languages.
// Using fetch in browser or Node.js with node-fetch async function formatCode(code, language = null, options = {}) { try { const response = await fetch('https://web-formatter.com/api/v2/format', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ code, language, options: { indentSize: 2, useTabs: false, minify: false, ...options } }) }); // Check rate limit headers const rateLimit = { limit: parseInt(response.headers.get('X-RateLimit-Limit') || '100'), remaining: parseInt(response.headers.get('X-RateLimit-Remaining') || '0'), resetSeconds: parseInt(response.headers.get('X-RateLimit-Reset') || '0') }; console.log(`Rate limit: ${rateLimit.remaining}/${rateLimit.limit} requests remaining`); // Handle rate limiting if (response.status === 429) { const retryAfter = parseInt(response.headers.get('Retry-After') || '60'); throw new Error(`Rate limit exceeded. Try again in ${retryAfter} seconds.`); } // Handle other errors if (!response.ok) { if (response.status === 413) { throw new Error('Payload too large. Code exceeds the maximum size limit.'); } else if (response.status === 422) { throw new Error('Code could not be formatted due to syntax errors.'); } else if (response.status === 500) { throw new Error('Server error occurred. Please try again later.'); } throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); if (!data.success) { throw new Error(data.error || 'Unknown error occurred'); } return data; } catch (error) { console.error('Error formatting code:', error); throw error; } } // Example with advanced retry logic for rate limits async function formatWithRetry(code, language = null, options = {}, maxRetries = 3) { let retries = 0; while (retries < maxRetries) { try { return await formatCode(code, language, options); } catch (error) { if (error.message.includes('Rate limit exceeded') && retries < maxRetries - 1) { retries++; const retrySeconds = parseInt(error.message.match(/in (\d+) seconds/)[1]) || 60; console.log(`Rate limited. Waiting ${retrySeconds} seconds before retry ${retries}...`); await new Promise(resolve => setTimeout(resolve, retrySeconds * 1000)); } else { throw error; } } } } // Example usage (async () => { try { const code = `function hello() { console.log("Hello"); }`; const result = await formatWithRetry(code, 'javascript'); console.log('Formatted code:', result.formattedCode); console.log('Language detected:', result.language); console.log('Validation:', result.validation); console.log('Stats:', result.stats); } catch (error) { console.error('Failed to format code:', error.message); } })();
Rate Limits
Our API is free to use with reasonable rate limits to ensure fair usage for all users.
- 100 requests per minute
- 1,000 requests per day
- Maximum code size: 1MB
- No API key required
Code Formatting API
Endpoint
POST /api/v2/format
Rate Limits
- 100 requests per minute
- 1,000 requests per day
- Maximum request size: 5MB
Request Format
Send a JSON object with the following properties:
code
*language
options
Options Object
indentSize
useTabs
removeComments
minify
validateOnly
Response Format
The API returns a JSON object with the following properties:
success
formattedCode
language
validation
stats
error
Example Request
fetch('https://web-formatter.com/api/v2/format', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ code: 'function example(a,b) {if(a>b) { return a; }else {return b;}}', language: 'javascript', options: { indentSize: 2, useTabs: false } }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Example Response
{ "success": true, "language": "javascript", "formattedCode": "function example(a, b) {\n if (a > b) {\n return a;\n } else {\n return b;\n }\n}", "validation": { "valid": true, "messages": ["Code structure looks valid"] }, "stats": { "originalSize": 65, "formattedSize": 78, "lines": 7 } }
Error Responses
400 Bad Request
Returned when the request is invalid (missing required fields, invalid JSON, etc.)
{ "success": false, "error": "Missing required field: code" }
413 Payload Too Large
Returned when the request exceeds the maximum size limit (5MB)
{ "success": false, "error": "Code size exceeds the maximum limit of 5MB" }
422 Unprocessable Entity
Returned when the code cannot be formatted (syntax errors, unsupported language features)
{ "success": false, "error": "Unable to format code: Syntax error at line 5, column 10", "language": "javascript", "validation": { "valid": false, "messages": ["Unexpected token at line 5, column 10"] } }
429 Too Many Requests
Returned when rate limits are exceeded
{ "success": false, "error": "Rate limit exceeded. Please try again later." }
Headers included in the response:
X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 38 Retry-After: 38
500 Internal Server Error
Returned when an unexpected server error occurs
{ "success": false, "error": "Internal server error. Please try again later." }
Supported Languages
Our API supports formatting for a wide range of programming languages and file formats:
Language Support Notes
While we support all the languages listed above, formatting quality may vary between languages. Core languages (HTML, CSS, JavaScript, JSON) have the most comprehensive formatting support. The auto-detection feature works best on these languages as well.
Example Code for Formatting
Here are examples of unformatted code for different languages that you can use to test the API:
<!DOCTYPE html> <html><head><title>Example Page</title><meta charset="UTF-8"></head><body><div class="container"><h1>Hello World</h1><p>This is an <strong>example</strong> of HTML code that needs formatting.</p><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul></div></body></html>