Sorting OpenAPI 3 Specs by Paths

OpenAPI is a the new emerging standard in API definitions and documentations.

It’s based on a Specification File structured in Json, and a few editors and viewer tools are popping up here and there.

Unfortunately something that seems pretty inconsistent is the sorting of the paths in the viewer against the editor. The specifications leave to the writer to decide in which order the API Paths should be sorted, but most of the editors doesn’t allow to reorder the paths inside of the Json file.

So, I made this small-and-ugly script to sort the PATHS inside of an OpenAPI json file alphabetically, which seems a pretty practical approach even in documentations.

It reads a file called openapi.json and writes out a file called openapi_sorted.json.

Feel free to use it as you like.

<?php

##
## Small tool to sort the paths inside an OpenAPI definition file
## Taken from https://andrea.brancatelli.it/
##

$mainObject = json_decode(file_get_contents("openapi.json"));

$paths = get_object_vars($mainObject-&gt;paths);
ksort($paths);

$mainObject-&gt;paths = new StdClass();

foreach ($paths as $eachPath =&gt; $eachValue) {
	$mainObject-&gt;paths-&gt;$eachPath = $eachValue;
}

file_put_contents("openapi_sorted.json", json_encode($mainObject,
	JSON_PRETTY_PRINT |
	JSON_UNESCAPED_SLASHES |
	JSON_UNESCAPED_UNICODE));