Huachao / vscode-restclient

REST Client Extension for Visual Studio Code
https://marketplace.visualstudio.com/items?itemName=humao.rest-client
MIT License
5.3k stars 443 forks source link

Is there a way to import saved requests from postman? #563

Open rohitkrishna094 opened 4 years ago

rohitkrishna094 commented 4 years ago

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

Thanks

Huachao commented 4 years ago

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

rafek1241 commented 4 years ago

@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...

momon commented 4 years ago

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.

alfathdirk commented 3 years ago

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

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

rohitkrishna094 commented 3 years ago

Thanks, will try it out. 👍

ScottRFrost commented 2 years ago

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.

tecty commented 1 year ago

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()
niemyjski commented 1 year ago

Any updates on this?

ScottRFrost commented 1 year ago

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!

bmrussell commented 1 year ago

@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 
aligjonatas commented 1 year ago

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!

hahndorf commented 1 year ago

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

danishjoseph commented 1 year ago

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

ScottRFrost commented 1 year ago

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.

tlunsfordCXP commented 7 months ago

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?

bmrussell commented 6 months ago

Ugh. What is the latest, greatest alternative?

Try httpyac. It's great

raffian commented 5 months ago

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