vscode-restclient icon indicating copy to clipboard operation
vscode-restclient copied to clipboard

Is there a way to import saved requests from postman?

Open rohitkrishna094 opened this issue 4 years ago • 17 comments

Is there a way to import postman collections into .http files so we can use them in vscode-restclient?

Thanks

rohitkrishna094 avatar Apr 17 '20 18:04 rohitkrishna094

@rohitkrishna094 nice suggestion, I am considering the feature that supports importing requests of postman, swagger and HAR format.

Huachao avatar Apr 18 '20 02:04 Huachao

@Huachao @rohitkrishna094 Regards this thing - I'm working on it from time to time: https://github.com/rafek1241/vscode-restclient/tree/feature/import-documents Still in progress but at least documents are parsed. It will take much time because there's still wrap up of the importer architecture, resign from postman-collection dependency and use our-own typescript interfaces...

rafek1241 avatar Aug 24 '20 20:08 rafek1241

Actually, synchronizing with Postman would be key for us, not sure if that's just a very specific case scenario, but the reason we keep postman is because it is very easy and quick to reference things in a team environment and to provide quick examples to others (not just devs) on how to work with our API's.

However, using this within VSC for a developer is MUCH MUCH faster and can leverage much more of what's already available to us within the app itself. So if there was also a way to export or sync to postman stuff we've already setup as tests locally that would be fantastic.

momon avatar Oct 01 '20 12:10 momon

@rohitkrishna094 im created simple generator vscode-rest from postman json.. maybe it helps you

https://github.com/alfathdirk/postman-to-vscode-rest-client

alfathdirk avatar May 04 '21 18:05 alfathdirk

Thanks, will try it out. 👍

rohitkrishna094 avatar May 24 '21 01:05 rohitkrishna094

https://github.com/alfathdirk/postman-to-vscode-rest-client doesn't appear to work any longer, at least on Windows 11 when exporting a Collections V2 json file from PostMan 10.2

npm -g i vsrest-postman-generator followed by npx vsrest MyCollectionFileName.json runs for a moment, then just returns without doing anything.

I tried with PowerShell, Command Prompt, and Git Bash.

ScottRFrost avatar Nov 10 '22 00:11 ScottRFrost

write a simple python script to do the job..

#! /usr/bin/env python3

import json
import sys

def toInt(s):
    try:
        return int(s)
    except Exception as e:
        return s

data = json.load(open(sys.argv[1]))
for item in data["item"]:
    print("###")
    print("# @name", item["name"])
    request = item["request"]
    print(request["method"], request["url"]["raw"])
    if "body" in request:
        print("Content-Type: application/json")
        print()
        if "raw" in request["body"]:
            body = json.loads(request["body"]["raw"])
            print(json.dumps(body, indent=2))
        elif "formdata" in request["body"]:
            body = dict(((el["key"], toInt(el["value"]))
                         for el in request["body"]["formdata"]))
            print(json.dumps(body, indent=2))
    print()

tecty avatar Mar 10 '23 09:03 tecty

Any updates on this?

niemyjski avatar May 29 '23 12:05 niemyjski

A competitor to this app / extension called ThunderClient just went paid only, so I'm back to looking for alternatives. Being able to import my requests would be a big help in that regard!

ScottRFrost avatar Jun 01 '23 17:06 ScottRFrost

@ScottRFrost try these shell scripts. Pass the name of the thunderclient collection .json file.

extract

#!/usr/bin/env bash
METHOD=$(cat $1 | (jq ".requests[] | select(.name == \"$2\").method") | sed --expression 's/\"//g')
URL=$(cat $1 | (jq ".requests[] | select(.name == \"$2\").url") | sed --expression 's/\"//g' | sed --expression 's/{{/{{$dotenv %/g')
HEADERS=$(cat $1 | (jq ".requests[] | select(.name == \"$2\").headers[] | [.name, .value] | @csv" ) | sed --expression 's/"//g' | sed --expression 's/\\//g' | sed --expression 's/,/: /g')
BODY=$(cat $1 | (jq ".requests[] | select(.name == \"$2\").body.raw")  | sed --expression 's/\\n//g' | sed --expression 's/\\//g' | sed --expression 's/^"//g' | sed --expression 's/"$//g')


echo "$METHOD $URL HTTP/1.1"
echo $HEADERS
echo

if [ "$BODY" != "null" ]; then
    echo $BODY
fi

extract-all

#!/usr/bin/env bash

(cat "$1" | jq -c '.requests[] | .name' | sed --expression 's/"//g') | \
while read r; do
  extract "$1" "$r" > "$r.http"
done 

bmrussell avatar Aug 19 '23 08:08 bmrussell

Guys, I wrote a PowerShell script to import different types of nodes. For example, sometimes you'll see exports like this:

"item": [
    {
        "name": "Method-Name",
        "request": { ... 
        }
    }
]

And another time like this:

"item": [
    {
        "name": "Folder-Name",
        "item": [
            {
                "name": "Sub-Folder-Name",
                "item": [
                    {
                        "name": "Method-Name",
                        "request": { ... 
                        }
                    }
                ]
            }
        ]
    }
]

Ps1 script:

# Carregar o conteúdo do JSON a partir de um arquivo
$jsonFilePath = "C:\Temp\exportThunder\thunder-collection_postman.json" # set file path and name here!
$jsonContent = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json

# Obtendo o nome do arquivo de entrada sem a extensão
$baseFileName = [System.IO.Path]::GetFileNameWithoutExtension($jsonFilePath)

# Criar o caminho completo para o arquivo de saída
$outputFilePath = Join-Path (Get-Item $jsonFilePath).Directory "$baseFileName.rest"

# Função para formatar a saída do bloco de request
function Format-RequestBlock($request, $eventName) {
    $requestName = $request.name
    $requestMethod = $request.request.method
    $requestUrl = $request.request.url.raw
    $requestBody = $request.request.body.raw
    $requestContentType = "application/" + $request.request.body.options.raw.language

    $output = @"
### $eventName
# @name $requestName
$requestMethod $requestUrl HTTP/1.1
Content-Type: $requestContentType
$requestBody
"@
    return $output
}

# Criar o novo arquivo e escrever as saídas formatadas
$output = @()
foreach ($item in $jsonContent.item) {
    if ($item.item -ne $null) {

        Write-Host "Tag $item.item possui array"
        # Chamar a função recursivamente se a propriedade 'item' existir
        foreach ($subItem in $item.item) {
            if ($subItem.item -ne $null) {
                foreach ($internalItem in $subItem.item) {
                    
                    Write-Host "Internal item $internalItem.item"

                    $formattedRequest = Format-RequestBlock -request $internalItem -eventName $jsonContent.info.name
                    $output += $formattedRequest
                    $output += "# ----------------------------------"
                    $output += ""
                }
            }
            else {
                $formattedRequest = Format-RequestBlock -request $subItem -eventName $jsonContent.info.name
                $output += $formattedRequest
                $output += "# ----------------------------------"
                $output += ""
            }
        }
    } else {

        Write-Host "Tag $item.item NAO possui array"

        $formattedRequest = Format-RequestBlock -request $item -eventName $jsonContent.info.name
        $output += $formattedRequest
        $output += "# ----------------------------------"
        $output += ""
    }
}


$output | Out-File -FilePath $outputFilePath

Write-Host "Arquivo gerado com sucesso em $outputFilePath"

To execute:

  1. Set the filePath inside the .ps1 script.
  2. Execute the script.
  3. The output will be a file with the same name but with a different extension.

I hope this helps someone! If anyone wants to make improvements, feel free to do so!

aligjonatas avatar Aug 29 '23 18:08 aligjonatas

I also wrote a PowerShell script to convert Postman export json files to http files. It's called ConvertFrom-PostmanCollection.ps1 and is part of my repo: https://github.com/hahndorf/hacops

hahndorf avatar Sep 01 '23 08:09 hahndorf

Check out my implementation in this PR https://github.com/Huachao/vscode-restclient/pull/1207

danishjoseph avatar Oct 14 '23 01:10 danishjoseph

Check out my implementation in this PR #1207

You may be wasting your time. This project hasn't had a release in 16 months now.

ScottRFrost avatar Oct 16 '23 21:10 ScottRFrost

Check out my implementation in this PR #1207

You may be wasting your time. This project hasn't had a release in 16 months now.

Ugh. What is the latest, greatest alternative?

tlunsfordCXP avatar Apr 16 '24 20:04 tlunsfordCXP

Ugh. What is the latest, greatest alternative?

Try httpyac. It's great

bmrussell avatar Apr 16 '24 20:04 bmrussell

I'm switching to CURL, should be safe from surprise subscription fees unless private equity buys it.

raffian avatar Jun 14 '24 00:06 raffian