Vim/NeoVim as a (very) simple REST client

joaomarcusc

João

Posted on April 15, 2021

Vim/NeoVim as a (very) simple REST client

Whenever you need to test APIs, you can probably resort to nice GUIs like Postman or Insomnia. They let you easily create separate projects, separate API paths, and so on. I do not like to leave my editor so often, so sometimes I just want to do the API calls inside it. If you use Vim, you can just run cUrl, httpie or some other HTTP client and paste the output on your buffer.

The following function is very handy because you can use pretty much any shell command you want and the output will be handily updated in your editor.

function! Exec_on_term(cmd, pos)
  exec "normal! ma"
  let backup_a=@a
  let backup_b=@b
  let sep = "------"
  exec "normal! ?".sep."\<CR>jV/".sep."\<CR>k\"ay"
  exec "normal! /".sep."\<CR>jO"
  if a:pos == "next"
      exec "normal! O".sep
      exec "normal! jddkko"
  endif
  exec "normal! V/".sep."\<CR>kdO"
  let @b=system(@a)
  execute "put b"
  execute "normal! ?".sep."\<CR>jdd"
  exec "normal 'a"
  let @b=backup_b
  let @a=backup_a
endfunction
nnoremap <Leader>dr :call Exec_on_term("normal", "curr")<CR>
vnoremap <F6> :<c-u>call Exec_on_term("visual", "curr")<CR>
nnoremap <Leader>dn :call Exec_on_term("normal", "next")<CR>
Enter fullscreen mode Exit fullscreen mode

For example, if you have the following buffer contents:

-----------
curl -H "Content-Type: application/json" \
-X POST  \
https://reqbin.com/echo/post/json \
-s -d '{"sample": "value"}'
-----------
output will be shown here
----------------
Enter fullscreen mode Exit fullscreen mode

You just need to go anywhere between the first "-------" line and the second "------" line, and type <Leader>dr (in my Vim config, Leader is the comma character, so ,dr here. It will run the command and show the output between the second and the third "-------" lines:

----------------
curl -H "Content-Type: application/json" \
-X POST  \
https://reqbin.com/echo/post/json \
-s -d '{"sample": "value"}'
----------------
{"success":"true"}
----------------
Enter fullscreen mode Exit fullscreen mode

If you change the command, it will replace the output. If you do not want to replace the contents, you can add a new entry by using <Leader>dn:

----------------
curl -H "Content-Type: application/json" \
-X POST  \
https://reqbin.com/echo/post/json \
-s -d '{"sample": "value"}'
----------------
{"success":"true"}
-----------
output will be shown here
---------------
Enter fullscreen mode Exit fullscreen mode

You can also run any CLI command, like Python code by using python -c:

---------------------
python -c '
import os
print("this is a python script")
'
---------------------
this is a python script
---------------------
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
joaomarcusc
João

Posted on April 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related