From 7cc5c9b0865f323f451fac2275f084aebcd7316e Mon Sep 17 00:00:00 2001 From: bgoosmanviz <78885081+bgoosmanviz@users.noreply.github.com> Date: Sun, 27 Oct 2024 16:39:43 -0400 Subject: [PATCH 1/2] Update proxy.ex with more examples Added example from https://news.livebook.dev/ `Livebook 0.13: expose an HTTP API from your notebook` --- lib/kino/proxy.ex | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/lib/kino/proxy.ex b/lib/kino/proxy.ex index 1894ad7d..7411575b 100644 --- a/lib/kino/proxy.ex +++ b/lib/kino/proxy.ex @@ -70,6 +70,43 @@ defmodule Kino.Proxy do > end > end) > ``` + + ### Leveraging Plug for APIs with Kino.Proxy + + You can also provide a module plug as an argument to Kino.Proxy.listen/1, like this: + + defmodule MyPlug do + def init([]), do: false + + def call(conn, _opts) do + Plug.Conn.send_resp(conn, 200, "hello world!") + end + end + + Kino.Proxy.listen(MyPlug) + + Since our API handler is a plug, we can leverage other plugs. For example, here's how to use Plug.Router to handle multiple endpoints: + + defmodule ApiRouter do + use Plug.Router + + plug :match + plug :dispatch + + get "/hello" do + send_resp(conn, 200, "hello from router") + end + + get "/echo/:message" do + send_resp(conn, 200, String.upcase(message)) + end + + match _ do + send_resp(conn, 404, "oops, not found") + end + end + + Kino.Proxy.listen(ApiRouter) """ @type plug() :: From c832a314f6653879c6fa57001e19e32f3c808ca9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 28 Oct 2024 08:09:29 +0100 Subject: [PATCH 2/2] Update proxy.ex --- lib/kino/proxy.ex | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/kino/proxy.ex b/lib/kino/proxy.ex index 7411575b..1b7eed2f 100644 --- a/lib/kino/proxy.ex +++ b/lib/kino/proxy.ex @@ -29,7 +29,6 @@ defmodule Kino.Proxy do Using the proxy feature, we can use Livebook apps to build APIs. For example, we could provide a data export endpoint: - Kino.Proxy.listen(fn %{path_info: ["export", "data"]} = conn -> data = "some data" @@ -71,9 +70,10 @@ defmodule Kino.Proxy do > end) > ``` - ### Leveraging Plug for APIs with Kino.Proxy + ## Using Plug modules with Kino.Proxy - You can also provide a module plug as an argument to Kino.Proxy.listen/1, like this: + You can also provide a module plug as an argument to `Kino.Proxy.listen/1`, + like this: defmodule MyPlug do def init([]), do: false @@ -85,7 +85,7 @@ defmodule Kino.Proxy do Kino.Proxy.listen(MyPlug) - Since our API handler is a plug, we can leverage other plugs. For example, here's how to use Plug.Router to handle multiple endpoints: + Or a more complex example, using `Plug.Router` to handle multiple endpoints: defmodule ApiRouter do use Plug.Router