>_nexthopreachable

JNCIA-DevOps: Junos REST API Automation

Ali Bahadır Coşkun5 min read

Junos has a built-in REST API. It runs over plain HTTP, exposes RPC calls as endpoints, and accepts config as XML in the request body. Because it's just HTTP, you don't need a Juniper-specific library: curl works, requests works, anything that can send a POST works. This lab covers reading operational state and pushing config to three routers without opening a single SSH session.

THE TOPOLOGY

The lab uses three vMX routers connected in a full mesh. A Linux host sits on the management network and runs the scripts. Loopbacks are 10.0.0.x/32. Management is out-of-band on the 192.168.100.0/24 network, which is what the API runs over.

ENABLING THE REST API

Configure these two lines on each router:

junos
set system services rest http port 3000set system services rest enable-explorer

enable-explorer gives you a browser UI at http://<router-ip>:3000 where you can browse available RPCs. Not something you'd use in production, but in a lab it's a decent way to find what RPC calls exist before writing a script around them. The base config also sets up a lab user and enables SSH. Commit everything, and the API is live.

STEP 1: VERIFY WITH CURL

Make sure the API is actually responding before writing any Python.

bash
curl -s -u lab:lab123 http://192.168.100.11:3000/rpc/get-software-information | head -20

If it works, you get XML back with <host-name>, <product-model>, Junos version, all that. If it doesn't work, the usual suspects are wrong IP on fxp0, wrong password, or the REST config wasn't committed properly. The endpoint format is /rpc/<rpc-name>. get-software-information maps to show version basically. Most show commands have an equivalent RPC name, and the explorer UI helps you find them if you don't know the name.

STEP 2: PUSH OSPF TO ALL THREE ROUTERS

Pushing config is a POST to /rpc with an XML payload wrapping your set commands. Junos processes them in order: lock, load, commit, unlock. All in one request. stop-on-error=1 in the URL matters. Without it, Junos keeps processing RPC calls even after one fails, so a failed lock could still be followed by a commit. OSPF config is the same on all three routers, so there's no per-device dict. One block, one loop:

python
import requestsfrom requests.auth import HTTPBasicAuthDEVICES = {    "R1": "192.168.100.11",    "R2": "192.168.100.12",    "R3": "192.168.100.13",}AUTH = HTTPBasicAuth("lab", "lab123")PORT = 3000OSPF_SET = """set protocols ospf area 0 interface ge-0/0/0.0set protocols ospf area 0 interface ge-0/0/1.0set protocols ospf area 0 interface lo0.0 passive"""for name, ip in DEVICES.items():    url = f"http://{ip}:{PORT}/rpc?stop-on-error=1"    payload = f"""<lock-configuration/><load-configuration action="set" format="text">  <configuration-set>{OSPF_SET}  </configuration-set></load-configuration><commit/><unlock-configuration/>"""    r = requests.post(url, auth=AUTH,                      headers={"Content-Type": "application/xml"},                      data=payload, timeout=30)    print(f"{name}: HTTP {r.status_code}")

STEP 3: VERIFY OSPF VIA REST

Before touching the CLI, pull neighbor and route state from HOST1 using a Python script. Both calls are GET requests, and the Accept: application/json header tells Junos to return JSON instead of XML. Create verify_ospf.py on HOST1:

python
import requestsfrom requests.auth import HTTPBasicAuthDEVICES = {    "R1": "192.168.100.11",    "R2": "192.168.100.12",    "R3": "192.168.100.13",}AUTH = HTTPBasicAuth("lab", "lab123")PORT = 3000for name, ip in DEVICES.items():    nbr_url = f"http://{ip}:{PORT}/rpc/get-ospf-neighbor-information"    route_url = f"http://{ip}:{PORT}/rpc/get-route-information?protocol=ospf"    nbr = requests.get(nbr_url, auth=AUTH, headers={"Accept": "application/json"}, timeout=10)    route = requests.get(route_url, auth=AUTH, headers={"Accept": "application/json"}, timeout=10)    print(f"\n{name}")    print(f"neighbors: HTTP {nbr.status_code}")    if nbr.status_code == 200:        neighbors = nbr.json().get("ospf-neighbor-information", [{}])[0].get("ospf-neighbor", [])        for item in neighbors:            nbr_ip = item.get("neighbor-address", [{}])[0].get("data", "?")            state = item.get("ospf-neighbor-state", [{}])[0].get("data", "?")            print(f"{nbr_ip} -> {state}")    print(f"routes: HTTP {route.status_code}")    if route.status_code == 200:        tables = route.json().get("route-information", [{}])[0].get("route-table", [])        for table in tables:            routes = table.get("rt", [])            for item in routes:                prefix = item.get("rt-destination", [{}])[0].get("data", "?")                print(prefix)
bash
python3 verify_ospf.py

Expected:

text
R1neighbors: HTTP 20010.0.12.2 -> Full10.0.13.2 -> Fullroutes: HTTP 20010.0.0.2/3210.0.0.3/32R2neighbors: HTTP 20010.0.12.1 -> Full10.0.23.2 -> Fullroutes: HTTP 20010.0.0.1/3210.0.0.3/32R3neighbors: HTTP 20010.0.13.1 -> Full10.0.23.1 -> Fullroutes: HTTP 20010.0.0.1/3210.0.0.2/32

The script parses the JSON response and prints neighbor addresses with their state, and the OSPF-learned prefixes per router. Worth noting: the Accept: application/json header is what switches the response format. The default is XML. Junos wraps every value in a list with a data key, which is why the parsing looks a bit nested.

VERIFY OSPF

Optional CLI check on any router:

text
lab@R1> show ospf neighborAddress          Interface              State     ID               Pri  Dead10.0.12.2        ge-0/0/0.0             Full      10.0.0.2         128    3710.0.13.2        ge-0/0/1.0             Full      10.0.0.3         128    37
text
lab@R1> show route protocol ospfinet.0: 12 destinations, 12 routes (12 active, 0 holddown, 0 hidden)+ = Active Route, - = Last Active, * = Both10.0.0.2/32        *[OSPF/10] 00:01:14, metric 1                    > to 10.0.12.2 via ge-0/0/0.010.0.0.3/32        *[OSPF/10] 00:01:14, metric 1                    > to 10.0.13.2 via ge-0/0/1.0

Optional ping from R1:

text
lab@R1> ping 10.0.0.3 source 10.0.0.1 count 3PING 10.0.0.3 (10.0.0.3): 56 data bytes64 bytes from 10.0.0.3: icmp_seq=0 ttl=64 time=2.341 ms64 bytes from 10.0.0.3: icmp_seq=1 ttl=64 time=1.876 ms64 bytes from 10.0.0.3: icmp_seq=2 ttl=64 time=2.104 ms

THAT'S IT!

REST API is fine for a quick read or a one-off push, but I didn't really like it for anything more than that. Error handling felt off to me: you get HTTP 200 even when your commit fails, and you have to dig into the response body yourself to find out what went wrong. No session management either. I'd rather use PyEZ, which wraps NETCONF and handles all of that. dev.config.load() takes care of the lock, load, commit, and unlock without writing a single XML tag.