Search

Dark theme | Light theme

April 25, 2025

Nushell Niceties: Posting JSON to an HTTP Endpoint

The http command in Nushell can be used to interact with HTTP endpoints. You can post data to an endpoint using the post subcommand. If you want to post JSON data than you can simply use a record data structure and use the argument --content-type application/json (or the shorthand -t application/json). Nushell will automatically convert the record data structure to JSON and use it as the body of the HTTP request.

In the following example we post a record data structure to the https://httpbin.org/anything endpoint. The record data structure is defined as last argument after the URL:

# You can post JSON data to an endpoint.
# To indicate the content type is JSON
# you can use the --content-type application/json argument.
# After the URL you can specify the data to post
# using a record data structure.
http post --content-type application/json https://httpbin.org/anything {
    name: mrhaki,
    age: 51,
    city: Tilburg
}

The record data structure can be created with variables and commands:

# You can use variables and command in the record data structure.
const username = 'mrhaki'
const firstName = 'Hubert'
const keyLastName = 'lastName'

http post --content-type application/json --full https://httpbin.org/anything {
    name: $username,
    firstName: ($firstName | str downcase),
    $keyLastName: 'Klein Ikkink'
}

Instead of defining the data directly in the http post command you can also create the record data structure first and then pass it to the http post command as last argument:

# The record data structure can be created first and
# then passed to the http post command as last argument.
const data = {
    os: 'MacOS',
    shells: ['Nushell', 'PowerShell']
}

http post --content-type application/json https://httpbin.org/anything $data

You can also use input redirection to pass the record data structure to the http post command. In the following example we pass a record data structure to the http post command using input redirection:

# You can pipe the record data structure to the http post command.
{ username: 'mrhaki' } | http post --content-type application/json https://httpbin.org/anything

Instead of defining the record structure directly as input you can also use the content of a file with JSON data:

# You can read the content of a file with JSON data and
# pass it to the http post command as input using pipes.
{ username: 'mrhaki' } | save data.json
open --raw data.json | http post --content-type application/json https://httpbin.org/anything

As a matter of fact you can use any command that outputs JSON as input to the http post command:

# You can use any command that outputs JSON
# as input to the http post command.
def createJSON [] {
    { username: 'mrhaki' }
}
createJSON | http post --content-type application/json https://httpbin.org/anything

Written with Nushell 0.103.0.