To link Elixir Livebook to a Phoenix application that is already running, you can follow these steps:
Install the Livebook package by adding {:livebook, "~> 0.2.0"}
to your mix.exs
file and running mix deps.get
.
In your Phoenix application, create a new Phoenix controller, for example LivebookController
, and define an action that will create and start a new Livebook server:
defmodule MyApp.LivebookController do
use MyApp.Web, :controller
def livebook(_conn, _params) do
{:ok, path} = Livebook.new(%{port: 0, storage: :ephemeral})
{:ok, %{
port: path.port,
url: "http://localhost:#{path.port}",
token: path.token
}}
end
end
This action will create a new Livebook server and return its port, URL, and token as a response.
In your Phoenix router (web/router.ex
), add a new route that will be handled by the LivebookController
:
scope "/api" do
post "/livebook", LivebookController, :livebook
end
In your frontend application, make an HTTP POST request to the /api/livebook
endpoint to start a new Livebook server, for example using the axios
library:
const response = await axios.post('/api/livebook')
const { port, url, token } = response.data
This will return the port, URL, and token of the Livebook server that was just created.
Open the Livebook UI by navigating to the URL returned by the /api/livebook
endpoint in your browser, and paste in the token when prompted. You should now be connected to the Livebook server that is linked to your Phoenix application.
You can then use the Livebook server to execute Elixir code and interact with your Phoenix application, for example by making HTTP requests to its endpoints or accessing its database.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-11-29 11:00:00 +0000
Seen: 7 times
Last updated: Apr 05 '22