Skip to content

Instantly share code, notes, and snippets.

@AdmTal
Created February 21, 2024 20:43
Show Gist options
  • Save AdmTal/6307c19764edb5817c1e9e484d266b23 to your computer and use it in GitHub Desktop.
Save AdmTal/6307c19764edb5817c1e9e484d266b23 to your computer and use it in GitHub Desktop.
Convert Postman collection export into VS Rest Client Files
import json
import os
# Function to sanitize filenames: lowercase and replace spaces with underscores
def sanitize_filename(name):
return name.replace("/", "-").replace(" ", "_").lower()
def create_rest_client_files(postman_collection, output_dir):
# Load Postman collection
with open(postman_collection) as file:
collection = json.load(file)
# Extract and format environment variables
environment_variables = {var["key"]: var["value"] for var in collection.get("variable", [])}
def extract_url(request):
"""Extract URL from request, accounting for variations in structure."""
if "url" in request:
if isinstance(request["url"], str):
return request["url"]
elif "raw" in request["url"]:
return request["url"]["raw"]
print(f'BAD : {request}')
return "URL_NOT_FOUND"
def handle_item(item, folder_path):
"""Recursively handle items, creating directories and files as necessary."""
if "item" in item: # Folder
new_folder_path = os.path.join(folder_path, sanitize_filename(item["name"]))
os.makedirs(new_folder_path, exist_ok=True)
for sub_item in item["item"]:
handle_item(sub_item, new_folder_path)
elif "request" in item: # Request
write_request(item, folder_path)
def write_request(item, folder_path):
"""Write request to a .http file."""
filename = sanitize_filename(item["name"]) + ".http"
file_path = os.path.join(folder_path, filename)
with open(file_path, "w") as file:
method = item["request"]["method"]
url = extract_url(item["request"])
headers = item["request"].get("header", [])
file.write(f"{method} {url}\n\n")
for header in headers:
file.write(f"{header['key']}: {header['value']}\n")
if "body" in item["request"] and item["request"]["method"] in ["POST", "PUT"]:
body = item["request"]["body"]
if body.get("mode") == "raw":
file.write("\n" + body["raw"])
# Create directories and files based on the Postman collection
for item in collection["item"]:
handle_item(item, output_dir)
# Write environment variables to .vscode/settings.json
vscode_folder = os.path.join(output_dir, ".vscode")
os.makedirs(vscode_folder, exist_ok=True)
settings_path = os.path.join(vscode_folder, "settings.json")
with open(settings_path, "w") as settings_file:
json.dump({"rest-client.environmentVariables": {"Local Dev": environment_variables}}, settings_file, indent=4)
input_dir = '/path/to/input/'
output_dir = '/path/to/output'
input_output_pairs = [
(f'{input_dir}/postman_collection.json', f'{output_dir}/vs_code_collection'),
]
for postman_collection, output_dir in input_output_pairs:
create_rest_client_files(postman_collection, output_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment