Introduction to Jupyter Server
Jupyter Server extends Jupyter Notebook functionalities by offering additional backend services and enabling richer API experiences. It allows developers to create custom, interactive computing environments tailored to their workflows. In this article, we delve into some of the most useful APIs provided by Jupyter Server, complete with example code snippets.
Useful Jupyter Server APIs
1. Listing Available Kernels
Retrieving all available kernels:
import requests
response = requests.get('http://localhost:8888/api/kernelspecs')
print(response.json())
2. Creating a New Kernel
Starting a new kernel instance:
import requests
data = {'name': 'python3'}
response = requests.post('http://localhost:8888/api/kernels', json=data)
print(response.json())
3. Interrupting a Kernel
Interrupting an existing kernel:
import requests
kernel_id = 'your_kernel_id'
response = requests.post(f'http://localhost:8888/api/kernels/{kernel_id}/interrupt')
print(response.status_code)
4. Executing Code
Running code within a specific kernel:
import requests
kernel_id = 'your_kernel_id'
headers = {'Content-Type': 'application/json'}
code = {'code': 'print("Hello, world!")'}
response = requests.post(f'http://localhost:8888/api/kernels/{kernel_id}/execute', headers=headers, json=code)
print(response.json())
5. Shutting Down a Kernel
Gracefully terminating an existing kernel:
import requests
kernel_id = 'your_kernel_id'
response = requests.delete(f'http://localhost:8888/api/kernels/{kernel_id}')
print(response.status_code)
Application Example: Creating a Custom Data Analysis Server
This example demonstrates how to utilize the introduced APIs to create a custom server for running data analysis jobs.
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
kernel_id = None
@app.route('/start', methods=['POST'])
def start_kernel():
global kernel_id
response = requests.post('http://localhost:8888/api/kernels', json={'name': 'python3'})
kernel_id = response.json()['id']
return jsonify(response.json())
@app.route('/execute', methods=['POST'])
def execute_code():
global kernel_id
code = request.json['code']
headers = {'Content-Type': 'application/json'}
response = requests.post(f'http://localhost:8888/api/kernels/{kernel_id}/execute', headers=headers, json={'code': code})
return jsonify(response.json())
@app.route('/stop', methods=['POST'])
def stop_kernel():
global kernel_id
response = requests.delete(f'http://localhost:8888/api/kernels/{kernel_id}')
kernel_id = None
return jsonify({'status': response.status_code})
if __name__ == '__main__':
app.run(debug=True)
In this application, we use Flask to create endpoints for starting, executing code in, and stopping a Jupyter kernel.
Note: Always ensure that Jupyter Server is running before executing these endpoints.
Hash: f704eece60335757bb0b824f41783e8c4761953cd77aba0552e4a6d2e10d112f