or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

code-formatters.mdconfiguration-system.mdfile-editor-formatting.mdfrontend-integration.mdhttp-api-client.mdhttp-api-handlers.mdindex.mdnotebook-formatting.md

http-api-client.mddocs/

0

# HTTP API Client

1

2

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

3

4

## Capabilities

5

6

### HTTP Client Class

7

8

Main client class for backend communication.

9

10

```typescript { .api }

11

class JupyterlabCodeFormatterClient {

12

request(path: string, method: string, body: any): Promise<any>;

13

getAvailableFormatters(cache: boolean): Promise<string>;

14

}

15

```

16

17

**Methods**:

18

- `request()` - Generic HTTP request method for API communication

19

- `getAvailableFormatters()` - Retrieves list of available formatters from backend

20

21

## Usage Examples

22

23

### Creating HTTP Client

24

25

```typescript

26

import JupyterlabCodeFormatterClient from './client';

27

28

// Create client instance

29

const client = new JupyterlabCodeFormatterClient();

30

```

31

32

### Making Generic Requests

33

34

```typescript

35

// GET request

36

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

37

38

// POST request with body

39

const formatRequest = {

40

code: ['def hello(): pass'],

41

formatter: 'black',

42

notebook: true,

43

options: { line_length: 88 }

44

};

45

46

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

47

```

48

49

### Getting Available Formatters

50

51

```typescript

52

// Get formatters without caching

53

const formattersResponse = await client.getAvailableFormatters(false);

54

const formatters = JSON.parse(formattersResponse);

55

56

console.log(formatters.formatters);

57

// Output: { black: { enabled: true, label: "Apply Black Formatter" }, ... }

58

59

// Get formatters with caching enabled

60

const cachedResponse = await client.getAvailableFormatters(true);

61

```

62

63

### Error Handling

64

65

```typescript

66

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

67

68

try {

69

const result = await client.request('format', 'POST', requestBody);

70

// Process successful response

71

} catch (error) {

72

if (error instanceof ServerConnection.ResponseError) {

73

console.error('Server error:', error.response.status, error.message);

74

} else {

75

console.error('Network error:', error);

76

}

77

}

78

```

79

80

## API Communication

81

82

### Base URL Construction

83

84

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

85

86

```typescript

87

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

88

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

89

90

const settings = ServerConnection.makeSettings();

91

const fullUrl = URLExt.join(

92

settings.baseUrl,

93

'jupyterlab_code_formatter', // plugin name

94

path // API endpoint

95

);

96

```

97

98

### Request Configuration

99

100

HTTP requests are configured with:

101

102

- **Server Settings**: Uses JupyterLab's ServerConnection settings

103

- **Authentication**: Automatic token-based authentication

104

- **Content Type**: JSON content type for POST requests

105

- **Error Handling**: Automatic HTTP status code checking

106

107

### Response Processing

108

109

The client processes responses with:

110

111

1. **Status Check**: Verifies HTTP status code (expects 200)

112

2. **Error Handling**: Throws `ServerConnection.ResponseError` for non-200 status

113

3. **Text Extraction**: Converts response to text format

114

4. **Return**: Returns response text (typically JSON string)

115

116

## API Endpoints

117

118

### Get Available Formatters

119

120

Retrieves list of available code formatters from backend.

121

122

**Endpoint**: `GET /jupyterlab_code_formatter/formatters[?cached]`

123

124

**Query Parameters**:

125

- `cached` (optional) - Use cached formatter availability checks

126

127

**Response Format**:

128

```json

129

{

130

"formatters": {

131

"black": {

132

"enabled": true,

133

"label": "Apply Black Formatter"

134

},

135

"isort": {

136

"enabled": true,

137

"label": "Apply Isort Formatter"

138

},

139

"yapf": {

140

"enabled": false,

141

"label": "Apply YAPF Formatter"

142

}

143

}

144

}

145

```

146

147

### Format Code

148

149

Sends code to backend for formatting with specified formatter.

150

151

**Endpoint**: `POST /jupyterlab_code_formatter/format[?cached]`

152

153

**Request Body**:

154

```json

155

{

156

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

157

"formatter": "black",

158

"notebook": true,

159

"options": {

160

"line_length": 88,

161

"string_normalization": true

162

}

163

}

164

```

165

166

**Query Parameters**:

167

- `cached` (optional) - Use cached formatter availability checks

168

169

**Response Format**:

170

```json

171

{

172

"code": [

173

{

174

"code": "def hello():\n pass\n"

175

}

176

]

177

}

178

```

179

180

**Error Response**:

181

```json

182

{

183

"code": [

184

{

185

"error": "Formatter error message"

186

}

187

]

188

}

189

```

190

191

## Caching Behavior

192

193

### Formatter Availability Caching

194

195

The client supports caching of formatter availability checks:

196

197

- **Cache Parameter**: `?cached` query parameter enables caching

198

- **Backend Caching**: Backend caches `importable` property checks

199

- **Performance**: Reduces repeated dependency checks for better performance

200

- **Cache Invalidation**: Cache persists for the duration of the server session

201

202

### Usage Patterns

203

204

```typescript

205

// First request - checks actual formatter availability

206

const initialCheck = await client.getAvailableFormatters(false);

207

208

// Subsequent requests - uses cached results

209

const cachedCheck = await client.getAvailableFormatters(true);

210

211

// Format requests can also use caching

212

const formatResult = await client.request(

213

'format?cached',

214

'POST',

215

JSON.stringify(formatRequest)

216

);

217

```

218

219

## Error Types

220

221

### Server Connection Errors

222

223

Handles various server connection error scenarios:

224

225

- **Network Errors**: Connection timeouts, network unavailable

226

- **HTTP Errors**: 404 (formatter not found), 500 (server error)

227

- **Authentication Errors**: 401/403 (authentication failures)

228

- **Response Errors**: Malformed response data

229

230

### Custom Error Handling

231

232

```typescript

233

try {

234

const result = await client.request('format', 'POST', requestBody);

235

return JSON.parse(result);

236

} catch (error) {

237

if (error instanceof ServerConnection.ResponseError) {

238

// Handle HTTP errors

239

switch (error.response.status) {

240

case 404:

241

console.error('Formatter not found');

242

break;

243

case 500:

244

console.error('Server error during formatting');

245

break;

246

default:

247

console.error('HTTP error:', error.response.status);

248

}

249

} else {

250

// Handle network errors

251

console.error('Network error:', error.message);

252

}

253

throw error;

254

}

255

```

256

257

## Integration with Formatters

258

259

### Frontend-Backend Coordination

260

261

The HTTP client coordinates between frontend formatters and backend services:

262

263

1. **Capability Discovery**: Queries available formatters on startup

264

2. **Dynamic Menu Updates**: Updates UI based on formatter availability

265

3. **Format Requests**: Sends code and configuration to backend

266

4. **Result Processing**: Handles formatted code and error responses

267

5. **State Management**: Manages formatting operation state

268

269

### Configuration Passing

270

271

The client passes configuration from frontend to backend:

272

273

- **Formatter Options**: Language-specific formatter settings

274

- **Context Information**: Notebook vs. file editor context

275

- **Cache Preferences**: Performance optimization settings

276

- **Error Handling**: Error suppression preferences