webformatter

API Documentation

Integrate Web Formatter's code formatting capabilities into your own applications with our powerful API.

Free Access
No API key required for basic usage

Get started quickly without any authentication requirements. Perfect for personal projects and prototypes.

Rate Limited
100 requests/minute, 1000 requests/day per IP

Fair usage limits to ensure availability for all users. Exceeding limits will result in temporary blocks.

API Status
Current API service status

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

POST
/format

Request Parameters

ParameterTypeRequiredDescription
codestringYesThe code to format
languagestringNoLanguage 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
optionsobjectNoFormatting options (see below)

Formatting Options

OptionTypeDefaultDescription
indentSizenumber2Number of spaces per indentation level
useTabsbooleanfalseUse tabs instead of spaces for indentation
minifybooleanfalseMinify the code instead of formatting it

Response Format

FieldTypeDescription
successbooleanIndicates if the request was successful
languagestringThe detected or specified language
formattedCodestringThe formatted or minified code
validationobjectValidation results with valid status and messages
statsobjectStatistics about the code (size, lines)
errorstringError message (only present if success is false)

Rate Limit Headers

HeaderDescription
X-RateLimit-LimitMaximum number of requests allowed per minute
X-RateLimit-RemainingNumber of requests remaining in the current time window
X-RateLimit-ResetTime in seconds until the rate limit resets
Retry-AfterTime in seconds to wait before retrying (only sent when rate limited)

Error Codes

Status CodeDescription
400Bad Request - Invalid parameters or missing required fields
413Payload Too Large - Code exceeds the 1MB size limit
422Unprocessable Entity - Code could not be formatted
429Too Many Requests - Rate limit exceeded
500Internal 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.

JavaScript / Node.js Example
Using fetch API (browser) or node-fetch (Node.js)
// 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.

Free Tier Limits
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:

Property
Type
Description
code *
string
The code to format
language
string
Programming language (optional, will be auto-detected if not provided)
options
object
Formatting options (optional)

Options Object

Property
Type
Description
indentSize
number
Number of spaces per indentation level (default: 2)
useTabs
boolean
Use tabs instead of spaces (default: false)
removeComments
boolean
Remove comments from the code (default: false)
minify
boolean
Minify the code instead of formatting (default: false)
validateOnly
boolean
Validate the code without formatting (default: false)

Response Format

The API returns a JSON object with the following properties:

Property
Type
Description
success
boolean
Whether the operation succeeded
formattedCode
string
The formatted code (only if successful)
language
string
The detected or specified language
validation
object
Code validation results
stats
object
Statistics about the code (sizes, line count)
error
string
Error message (only if unsuccessful)

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:

HTML
CSS
JavaScript
TypeScript
JSON
XML
SQL
YAML
Markdown
Python
PHP
Ruby
Go
Rust
Java
C#
C/C++
Shell Script
GraphQL
SCSS
LESS
Dart
Kotlin
R
Lua
Haskell
Perl
Assembly
Swift

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>
webformatter
© 2025 web-formatter.com