CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-jupyterlab-code-formatter

A JupyterLab extension to facilitate invocation of code formatters for multiple programming languages.

Pending
Overview
Eval results
Files

http-api-client.mddocs/

HTTP API Client

HTTP client for communication between JupyterLab frontend and Python backend with request handling, error management, and caching support.

Capabilities

HTTP Client Class

Main client class for backend communication.

class JupyterlabCodeFormatterClient {
  request(path: string, method: string, body: any): Promise<any>;
  getAvailableFormatters(cache: boolean): Promise<string>;
}

Methods:

  • request() - Generic HTTP request method for API communication
  • getAvailableFormatters() - Retrieves list of available formatters from backend

Usage Examples

Creating HTTP Client

import JupyterlabCodeFormatterClient from './client';

// Create client instance
const client = new JupyterlabCodeFormatterClient();

Making Generic Requests

// GET request
const response = await client.request('formatters', 'GET', null);

// POST request with body
const formatRequest = {
  code: ['def hello(): pass'],
  formatter: 'black',
  notebook: true,
  options: { line_length: 88 }
};

const result = await client.request('format', 'POST', JSON.stringify(formatRequest));

Getting Available Formatters

// Get formatters without caching
const formattersResponse = await client.getAvailableFormatters(false);
const formatters = JSON.parse(formattersResponse);

console.log(formatters.formatters);
// Output: { black: { enabled: true, label: "Apply Black Formatter" }, ... }

// Get formatters with caching enabled
const cachedResponse = await client.getAvailableFormatters(true);

Error Handling

import { ServerConnection } from '@jupyterlab/services';

try {
  const result = await client.request('format', 'POST', requestBody);
  // Process successful response
} catch (error) {
  if (error instanceof ServerConnection.ResponseError) {
    console.error('Server error:', error.response.status, error.message);
  } else {
    console.error('Network error:', error);
  }
}

API Communication

Base URL Construction

The client constructs API URLs using JupyterLab's server settings:

import { URLExt } from '@jupyterlab/coreutils';
import { ServerConnection } from '@jupyterlab/services';

const settings = ServerConnection.makeSettings();
const fullUrl = URLExt.join(
  settings.baseUrl,
  'jupyterlab_code_formatter', // plugin name
  path                         // API endpoint
);

Request Configuration

HTTP requests are configured with:

  • Server Settings: Uses JupyterLab's ServerConnection settings
  • Authentication: Automatic token-based authentication
  • Content Type: JSON content type for POST requests
  • Error Handling: Automatic HTTP status code checking

Response Processing

The client processes responses with:

  1. Status Check: Verifies HTTP status code (expects 200)
  2. Error Handling: Throws ServerConnection.ResponseError for non-200 status
  3. Text Extraction: Converts response to text format
  4. Return: Returns response text (typically JSON string)

API Endpoints

Get Available Formatters

Retrieves list of available code formatters from backend.

Endpoint: GET /jupyterlab_code_formatter/formatters[?cached]

Query Parameters:

  • cached (optional) - Use cached formatter availability checks

Response Format:

{
  "formatters": {
    "black": {
      "enabled": true,
      "label": "Apply Black Formatter"
    },
    "isort": {
      "enabled": true,
      "label": "Apply Isort Formatter"
    },
    "yapf": {
      "enabled": false,
      "label": "Apply YAPF Formatter"
    }
  }
}

Format Code

Sends code to backend for formatting with specified formatter.

Endpoint: POST /jupyterlab_code_formatter/format[?cached]

Request Body:

{
  "code": ["def hello():\n    pass"],
  "formatter": "black",
  "notebook": true,
  "options": {
    "line_length": 88,
    "string_normalization": true
  }
}

Query Parameters:

  • cached (optional) - Use cached formatter availability checks

Response Format:

{
  "code": [
    {
      "code": "def hello():\n    pass\n"
    }
  ]
}

Error Response:

{
  "code": [
    {
      "error": "Formatter error message"
    }
  ]
}

Caching Behavior

Formatter Availability Caching

The client supports caching of formatter availability checks:

  • Cache Parameter: ?cached query parameter enables caching
  • Backend Caching: Backend caches importable property checks
  • Performance: Reduces repeated dependency checks for better performance
  • Cache Invalidation: Cache persists for the duration of the server session

Usage Patterns

// First request - checks actual formatter availability
const initialCheck = await client.getAvailableFormatters(false);

// Subsequent requests - uses cached results
const cachedCheck = await client.getAvailableFormatters(true);

// Format requests can also use caching
const formatResult = await client.request(
  'format?cached', 
  'POST', 
  JSON.stringify(formatRequest)
);

Error Types

Server Connection Errors

Handles various server connection error scenarios:

  • Network Errors: Connection timeouts, network unavailable
  • HTTP Errors: 404 (formatter not found), 500 (server error)
  • Authentication Errors: 401/403 (authentication failures)
  • Response Errors: Malformed response data

Custom Error Handling

try {
  const result = await client.request('format', 'POST', requestBody);
  return JSON.parse(result);
} catch (error) {
  if (error instanceof ServerConnection.ResponseError) {
    // Handle HTTP errors
    switch (error.response.status) {
      case 404:
        console.error('Formatter not found');
        break;
      case 500:
        console.error('Server error during formatting');
        break;
      default:
        console.error('HTTP error:', error.response.status);
    }
  } else {
    // Handle network errors
    console.error('Network error:', error.message);
  }
  throw error;
}

Integration with Formatters

Frontend-Backend Coordination

The HTTP client coordinates between frontend formatters and backend services:

  1. Capability Discovery: Queries available formatters on startup
  2. Dynamic Menu Updates: Updates UI based on formatter availability
  3. Format Requests: Sends code and configuration to backend
  4. Result Processing: Handles formatted code and error responses
  5. State Management: Manages formatting operation state

Configuration Passing

The client passes configuration from frontend to backend:

  • Formatter Options: Language-specific formatter settings
  • Context Information: Notebook vs. file editor context
  • Cache Preferences: Performance optimization settings
  • Error Handling: Error suppression preferences

Install with Tessl CLI

npx tessl i tessl/pypi-jupyterlab-code-formatter

docs

code-formatters.md

configuration-system.md

file-editor-formatting.md

frontend-integration.md

http-api-client.md

http-api-handlers.md

index.md

notebook-formatting.md

tile.json