{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# REST API inside a notebook\n", "\n", "## Initial Setup\n", "\n", "Start by running all cells, which will launch a server on http://localhost:5001\n", "\n", "## REST API manifest\n", "\n", "A manifest is available of the nanoservice API at:\n", "* JSON: http://localhost:5001\n", "* Markdown: http://localhost:5001/?format=md \n", "\n", "## REST API Access\n", "\n", "Functions in the notebook are accessible via URLs formatted as `http://localhost:5001/api/{function_name}`\n", "Parameters will be strings unless you add typing to your params:\n", "\n", "### Example: Untyped Function Parameter\n", "```python\n", "def example_untyped(param):\n", " return f\"Received: {param}\"\n", "```\n", "URL: `http://localhost:5001/api/example_untyped?param=Hello`\n", "\n", "### Example: Typed Function Parameter\n", "```python\n", "def example_typed(param: int):\n", " return param * 2\n", "```\n", "URL: `http://localhost:5001/api/example_typed?param=5`\n", "\n", "### Example: Pitfall of Untyped Parameter\n", "```python\n", "def add_ten(value):\n", " return value + 10\n", "```\n", "URL: `http://localhost:5001/api/add_ten?value=5`\n", "\n", "This will result in an error because `value` is treated as a string, and you cannot add a string to a number.\n", "\n", "### Example: Untyped Parameter, cast string to int\n", "```python\n", "def add_ten(value):\n", " # better that the paramater had a type, but if we can't, we will cast to what we need just in time\n", " return int(value) + 10\n", "```\n", "URL: `http://localhost:5001/api/add_ten?value=5`\n", "\n", "By casting `value` to an integer, the function works as expected.\n", "\n", "## Customize\n", "\n", "You can define functions in any cell within the notebook. Once defined, functions become accessible through the REST API by their name, with parameters formatted in the URL.\n", "\n", "Modify and re-run any cell containing a function to update its implementation instantly. Changes are reflected immediately in the REST API, without needing to restart the server.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from notebook_nanoservice import NanoService\n", "service = NanoService(globals())\n", "service.start()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Server Management\n", "\n", "Uncomment and run the `service.stop()` cell. This action gracefully shuts down the server and frees up port 5001." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " #service.stop()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "from PIL import Image\n", "import seaborn as sns\n", "\n", "# Your functions. They are accessible by name from the REST API\n", "\n", "# Function 0: Test Single Boolean Parameter\n", "# Expects a single string parameter.\n", "# Example URL: http://localhost:5001/api/bool?value=False\n", "def bool(value: bool):\n", " return value\n", "\n", "# Function 1: Test Single String Parameter\n", "# Expects a single string parameter.\n", "# Example URL: http://localhost:5001/api/greet?name=John\n", "def greet(name: str):\n", " return f\"Hello, {name}!\"\n", "\n", "# Function 2: Test List of Strings\n", "# Expects a list of strings.\n", "# Example URL: http://localhost:5001/api/list_tags?tags[]=red&tags[]=blue&tags[]=green\n", "def list_tags(tags: list[str]):\n", " return tags\n", "\n", "# Function 3: Test Single String with a Literal Comma\n", "# Expects a string that may contain commas.\n", "# Example URL: http://localhost:5001/api/show_title?title=Hello%2C+World\n", "def show_title(title: str):\n", " return title\n", "\n", "# Function 4: Test List of Strings with Values Containing Commas\n", "# Expects a list of strings, where each string may contain encoded commas.\n", "# Example URL: http://localhost:5001/api/complex_tags?tags[]=red&tags[]=blue%2C+with+commas\n", "def complex_tags(tags: list[str]):\n", " return tags\n", "\n", "# Function 5: Test Single Integer Parameter\n", "# Expects a single integer parameter.\n", "# Example URL: http://localhost:5001/api/show_age?age=30\n", "def show_age(age: int):\n", " return age\n", "\n", "# Function 6: Test Single Float Parameter\n", "# Expects a single float parameter.\n", "# Example URL: http://localhost:5001/api/show_price?price=19.99\n", "def show_price(price: float):\n", " return price\n", "\n", "# Function 7: Test List of Integers\n", "# Expects a list of integers.\n", "# Example URL: http://localhost:5001/api/show_scores?scores[]=10&scores[]=20&scores[]=30\n", "def show_scores(scores: list[int]):\n", " return scores\n", "\n", "# Function 8: Test List of Floats\n", "# Expects a list of floats.\n", "# Example URL: http://localhost:5001/api/show_temperatures?temperatures[]=36.6&temperatures[]=37.1&temperatures[]=38.0\n", "def show_temperatures(temperatures: list[float]):\n", " return temperatures\n", "\n", "# Function 9: Test List of Strings\n", "# Expects a list of strings.\n", "# Example URL: http://localhost:5001/api/show_colors?colors[]=red&colors[]=blue&colors[]=green\n", "def show_colors(colors: list[str]):\n", " return colors\n", "\n", "# Function 10: Test Combination of String, Integer, and Float\n", "# Expects a combination of a string, an integer, and a float.\n", "# Example URL: http://localhost:5001/api/show_profile?name=John&age=30&height=5.9\n", "def show_profile(name: str, age: int, height: float):\n", " return {\n", " \"name\": name,\n", " \"age\": age,\n", " \"height\": height\n", " }\n", "\n", "# Function 11: Return a Pandas DataFrame\n", "# Example URL: http://localhost:5001/api/get_dataframe\n", "def get_dataframe():\n", " data = {\n", " 'Name': ['Alice', 'Bob', 'Charlie'],\n", " 'Age': [25, 30, 35],\n", " 'Gender': ['F', 'M', 'M']\n", " }\n", " df = pd.DataFrame(data)\n", " return df\n", "\n", "# Function 12: Ensure legacy Pandas DataFrames are supported\n", "# Example URL: http://localhost:5001/api/get_dataframe_legacy\n", "def get_dataframe_legacy():\n", " data = {\n", " 'Name': ['Alice', 'Bob', 'Charlie', 'Legacy'],\n", " 'Age': [25, 30, 35, 42],\n", " 'Gender': ['F', 'M', 'M', 'U']\n", " }\n", " df = pd.DataFrame(data)\n", " return df.to_dict(orient='records')\n", "\n", "# Function 13: Create a red square image\n", "# Example URL: http://localhost:5001/api/create_red_square?size=100\n", "def create_red_square(size: int):\n", " img = Image.new('RGB', (size, size), color='red')\n", " return img\n", "\n", "# Function 14: Create a simple bar chart\n", "# Example URL: http://localhost:5001/api/create_bar_chart\n", "def create_bar_chart():\n", " import matplotlib.pyplot as plt\n", " data = {'A': 10, 'B': 15, 'C': 7, 'D': 12}\n", " names = list(data.keys())\n", " values = list(data.values())\n", "\n", " fig, ax = plt.subplots()\n", " ax.bar(names, values)\n", " plt.close(fig)\n", " return fig\n", "\n", "# Function 15: Create a correlation matrix and show a heatmap\n", "# Example URL: http://localhost:5001/api/correlation_heatmap\n", "def correlation_heatmap():\n", " import matplotlib.pyplot as plt\n", "\n", " # Example data\n", " data = {\n", " 'A': [1, 2, 3, 4, 5],\n", " 'B': [5, 4, 3, 2, 1],\n", " 'C': [2, 3, 4, 5, 6]\n", " }\n", " df = pd.DataFrame(data)\n", " corr = df.corr()\n", "\n", " plt.figure(figsize=(10, 8))\n", " sns.heatmap(corr, annot=True, cmap=\"coolwarm\", fmt=\".2f\")\n", " plt.title(\"Correlation Heatmap for Numeric Columns\")\n", " return plt\n", "\n", "# Function 16: Return describe() of a DataFrame\n", "# Example URL: http://localhost:5001/api/get_dataframe_describe\n", "def get_dataframe_describe():\n", " data = {\n", " 'Name': ['Alice', 'Bob', 'Charlie'],\n", " 'Age': [25, 30, 35],\n", " 'Gender': ['F', 'M', 'M']\n", " }\n", " df = pd.DataFrame(data)\n", " return df.describe(include='all')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Test your function to make sure it works\n", "show_profile('M', 2020, 1.23)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "create_red_square(100)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "create_bar_chart()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "correlation_heatmap()" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.9" } }, "nbformat": 4, "nbformat_minor": 2 }