> ## Documentation Index
> Fetch the complete documentation index at: https://docs.riza.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Execute code

> Run a script in a secure, isolated environment. Scripts can read from `stdin` and write to `stdout` or `stderr`. They can access input files, environment variables and command line arguments.

<RequestExample>
  ```js Node theme={null}
  import Riza from '@riza-io/api';

  // Untrusted Python code, either written by 
  // a customer or a LLM.
  const python = `
  import sys
  import os

  if 'DEBUG' in os.environ:
      print('Reversing string...', file=sys.stderr)
  stdin = sys.stdin.read()
  print("".join(reversed(stdin)))
  `;

  const riza = new Riza();

  async function main() {
    const resp = await riza.command.exec({
      language: "python",
      code: python,
      stdin: "Hello", 
      env: {
        "DEBUG": "true",
      }
    });
    console.dir(resp, {depth: null});
  }

  main();
  ```

  ```py Python theme={null}
  from rizaio import Riza

  # Untrusted Python code, either written by
  # a customer or a LLM.
  CODE = """
  import sys
  import os

  if 'DEBUG' in os.environ:
      print('Reversing string...', file=sys.stderr)
  stdin = sys.stdin.read()
  print("".join(reversed(stdin)))
  """

  client = Riza()

  resp = client.command.exec(
      language="python",
      code=CODE,
      stdin="Hello",
      env={
          "DEBUG": "true",
      }
  )

  print(dict(resp))
  ```

  ```go Go theme={null}
  package main

  import (
      "context"
      "log"
      "log/slog"

      "github.com/riza-io/riza-api-go"
  )

  // Untrusted Python code, either written by 
  // a customer or a LLM.
  const code = `
  import sys
  import os

  if 'DEBUG' in os.environ:
      print('Reversing string...', file=sys.stderr)
  stdin = sys.stdin.read()
  print("".join(reversed(stdin)))
  `

  func main() {
      client := riza.NewClient()
      resp, err := client.Command.Exec(context.TODO(), riza.CommandExecParams{
          Language: riza.F(riza.CommandExecParamsLanguagePython),
          Code:     riza.F(code),
          Stdin:    riza.F("Hello"),
          Env:      riza.F(
              map[string]string{"DEBUG": "true"},
          ),
      })
      if err != nil {
          log.Fatal(err)
      }
      slog.Info(
          resp.Stdout, 
          "code", resp.ExitCode,
          "stderr", resp.Stderr,
      )
  }
  ```

  ```bash curl theme={null}
  curl https://api.riza.io/v1/execute \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $RIZA_API_KEY" \
      --data-binary @- << EOF
  {
      "language": "python",
      "code": "import sys\nimport os\n\nif 'DEBUG' in os.environ:\n    print('Reversing string...', file=sys.stderr)\nstdin = sys.stdin.read()\nprint(''.join(reversed(stdin)))",
      "stdin": "Hello",
      "env": {
          "DEBUG":"true"
      }
  }
  EOF
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
      "exit_code": 0,
      "stdout": "olleH",
      "stderr": "Reversing string..."
  }
  ```
</ResponseExample>


## OpenAPI

````yaml post /v1/execute
openapi: 3.0.3
info:
  title: Execute
  version: 0.1.4
servers:
  - url: https://api.riza.io
security:
  - bearerHttpAuthentication: []
paths:
  /v1/execute:
    post:
      tags:
        - Sandbox
      summary: Execute code
      description: >-
        Run a script in a secure, isolated environment. Scripts can read from
        `stdin` and write to `stdout` or `stderr`. They can access input files,
        environment variables and command line arguments.
      operationId: Sandbox_Execute
      requestBody:
        content:
          application/json:
            examples:
              Python:
                value:
                  language: PYTHON
                  code: print("Hello world!")
            schema:
              $ref: '#/components/schemas/ExecuteRequest'
        required: true
      responses:
        '200':
          content:
            application/json:
              examples:
                hello:
                  value:
                    id: ''
                    exit_code: 0
                    stdout: Hello, World!
                    stderr: ''
                    duration: 1
              schema:
                $ref: '#/components/schemas/ExecuteResponse'
          description: OK
        '401':
          content:
            application/json:
              examples:
                unauthenticated:
                  value:
                    code: 16
                    message: unauthenticated
              schema:
                $ref: '#/components/schemas/Status'
          description: Unauthenticated error response
      x-codeSamples:
        - lang: JavaScript
          source: >-
            import Riza from '@riza-io/api';


            const client = new Riza({
              apiKey: process.env['RIZA_API_KEY'], // This is the default and can be omitted
            });


            const response = await client.command.exec({ code: 'print("Hello
            world!")', language: 'PYTHON' });


            console.log(response.id);
        - lang: Python
          source: |-
            import os
            from rizaio import Riza

            client = Riza(
                api_key=os.environ.get("RIZA_API_KEY"),  # This is the default and can be omitted
            )
            response = client.command.exec(
                code="print(\"Hello world!\")",
                language="PYTHON",
            )
            print(response.id)
        - lang: Go
          source: |
            package main

            import (
              "context"
              "fmt"

              "github.com/riza-io/riza-api-go"
              "github.com/riza-io/riza-api-go/option"
            )

            func main() {
              client := riza.NewClient(
                option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("RIZA_API_KEY")
              )
              response, err := client.Command.Exec(context.TODO(), riza.CommandExecParams{
                Code: riza.F(`print("Hello world!")`),
                Language: riza.F(riza.CommandExecParamsLanguage("PYTHON")),
              })
              if err != nil {
                panic(err.Error())
              }
              fmt.Printf("%+v\n", response.ID)
            }
components:
  schemas:
    ExecuteRequest:
      properties:
        args:
          description: List of command line arguments to pass to the script.
          items:
            type: string
          type: array
        code:
          description: The code to execute.
          type: string
        env:
          additionalProperties:
            type: string
          description: Set of key-value pairs to add to the script's execution environment.
          type: object
        files:
          description: List of input files.
          items:
            $ref: '#/components/schemas/File'
          type: array
        http:
          $ref: '#/components/schemas/HTTP'
        language:
          description: The interpreter to use when executing code.
          enum:
            - python
            - javascript
            - typescript
            - ruby
            - php
          type: string
        limits:
          $ref: '#/components/schemas/Limits'
        runtime_revision_id:
          description: The ID of the runtime revision to use when executing code.
          type: string
        stdin:
          description: Input made available to the script via 'stdin'.
          type: string
      required:
        - language
        - code
      type: object
    ExecuteResponse:
      properties:
        duration:
          description: The execution time of the script in milliseconds.
          type: integer
        exit_code:
          description: >-
            The exit code returned by the script. Will often be '0' on success
            and non-zero on failure.
          type: integer
        id:
          description: The ID of the execution.
          type: string
        stderr:
          description: The contents of 'stderr' after executing the script.
          type: string
        stdout:
          description: The contents of 'stdout' after executing the script.
          type: string
      required:
        - id
        - exit_code
        - stdout
        - stderr
        - duration
      type: object
    Status:
      properties:
        code:
          description: >-
            The status code, which should be an enum value of
            [google.rpc.Code][google.rpc.Code].
          type: integer
        message:
          description: >-
            A developer-facing error message, which should be in English. Any
            user-facing error message should be localized and sent in the
            [google.rpc.Status.details][google.rpc.Status.details] field, or
            localized by the client.
          type: string
      type: object
    File:
      properties:
        contents:
          description: The contents of the file.
          type: string
        path:
          description: The relative path of the file.
          type: string
      type: object
    HTTP:
      description: Configuration for HTTP requests and authentication.
      properties:
        allow:
          description: List of allowed HTTP hosts and associated authentication.
          items:
            $ref: '#/components/schemas/HTTPAllow'
          type: array
      type: object
    Limits:
      description: Configuration for execution environment limits.
      properties:
        execution_timeout:
          description: The maximum time allowed for execution (in seconds). Default is 30.
          type: integer
        memory_size:
          description: The maximum memory allowed for execution (in MiB). Default is 128.
          type: integer
      type: object
    HTTPAllow:
      description: List of allowed HTTP hosts and associated authentication.
      properties:
        auth:
          $ref: '#/components/schemas/HTTPAuth'
        host:
          description: The hostname to allow.
          type: string
      type: object
    HTTPAuth:
      description: Authentication configuration for outbound requests to this host.
      properties:
        basic:
          $ref: '#/components/schemas/HTTPBasic'
        bearer:
          $ref: '#/components/schemas/HTTPBearer'
        header:
          $ref: '#/components/schemas/HTTPHeader'
        query:
          $ref: '#/components/schemas/HTTPQuery'
      type: object
    HTTPBasic:
      properties:
        password:
          type: string
        user_id:
          type: string
      type: object
    HTTPBearer:
      description: >-
        Configuration to add an 'Authorization' header using the 'Bearer'
        scheme.
      properties:
        token:
          description: 'The token to set, e.g. ''Authorization: Bearer <token>''.'
          type: string
      type: object
    HTTPHeader:
      properties:
        name:
          type: string
        value:
          type: string
      type: object
    HTTPQuery:
      properties:
        key:
          type: string
        value:
          type: string
      type: object
  securitySchemes:
    bearerHttpAuthentication:
      scheme: bearer
      type: http

````