Mantra Networking Mantra Networking

Batfish: REST API

Batfish: REST API
Created By: Lauren R. Garcia

Table of Contents

  • Overview
  • Authentication
  • Common Endpoints
  • Sample Workflow
  • Payload Format
  • Response Codes
  • Conclusion

Batfish REST API: Overview

What is the Batfish REST API?

The Batfish REST API is a web-based interface that enables network engineers and automation systems to programmatically interact with Batfish’s powerful network analysis engine. Instead of working solely through scripts or Python code, you can use standard HTTP requests—such as GET, POST, and DELETE—to analyze network configurations, validate routing, and detect configuration issues across multivendor environments. The API turns Batfish into a flexible service that can be embedded in any automated workflow or CI/CD pipeline.

Why Do You Need to Know About It?

Modern network infrastructures are dynamic and complex. Manual validation of device configurations and troubleshooting of network issues is both time-consuming and error-prone. Here’s why learning the Batfish REST API matters:

  • Automates Repetitive Network Validation: Integrate Batfish checks into your deployment process to catch misconfigurations before they cause outages.
  • Enables Continuous Compliance: Regularly audit network policies and security rules at scale, reducing risk of human error or drift.
  • Supports Multi-Platform Environments: Batfish supports configurations from vendors like Cisco, Juniper, Arista, and more. The API lets you analyze diverse networks from a single tool.
  • Improves Troubleshooting Efficiency: Instantly answer questions such as “Will these changes impact reachability?” or “Are all firewalls enforcing the intended policy?” using automated queries.
  • Ideal for DevOps and NetDevOps: If you’re integrating networking with app deployment and need reliable, automated change validation, the API fits seamlessly into CI/CD tools and custom dashboards.

How Does It Work?

The Batfish REST API operates as a service that you can reach over HTTP on your network or local server. Here’s how it functions in practice:

  • Network Creation: Organize your analysis by defining logical networks within Batfish.
  • Snapshot Uploads: Send device configuration files and topology data as “snapshots” to be analyzed.
  • Session Management: The API can maintain sessions, so several steps in a network analysis workflow can be tied together.
  • Question Execution: Submit “questions” (predefined analysis queries, such as reachability, loop detection, or policy compliance) against your network snapshot.
  • Structured Answers: The API returns results in structured formats (usually JSON), ready to be visualized, integrated with other systems, or acted upon in automation scripts.

Typical end-to-end usage involves:

  1. Deploying Batfish as a REST service.
  2. Uploading network data.
  3. Triggering specific analyses.
  4. Automating result interpretation and remediation.

The REST API provides a standardized, language-agnostic way to embed Batfish’s network intelligence anywhere you need it, making infrastructure automation more reliable, scalable, and secure.


Authentication

Before sending requests to the Batfish REST API, consider the following steps to ensure secure and proper access:

  1. Determine Authentication Requirements: By default, Batfish runs without authentication enabled. Check whether your deployment has authentication configured (for example, in shared or production environments).
  2. Review Authentication Configuration: If authentication is enabled, Batfish typically supports integration with third-party providers using standards like OIDC (OpenID Connect). This is managed through configuration files supplied to the server at startup.
  3. Obtain Access Credentials: Secure any necessary credentials or tokens as required by your deployment’s authentication method. This may involve authenticating against an identity provider or obtaining access tokens.
  4. Include Authorization Details in Requests: When authentication is active, add the proper Authorization header or token to your HTTP requests. For example:
    Authorization: Bearer <your-access-token>
        
  5. Use Secure Channels: Always communicate with the Batfish REST API over HTTPS, especially if authentication is required, to protect your credentials and data in transit.
  6. Verify Access on Each Request: If authentication is enabled, the API will reject unauthenticated or invalid requests with an appropriate error (such as HTTP 401 or 403). Double check your credentials or token if you receive such errors.

Consult your team's or organization's policies for additional authentication or access control requirements specific to your environment.

Common Endpoints

This section describes how to interact with the most frequently used Batfish REST API endpoints, guiding you step by step through typical network analysis workflows:

  1. Create or Select a Network:
    Use this endpoint to create a new logical environment for your analysis.
    POST /networks
    Payload Example:
    {
      "name": "sample_network"
    }
        
  2. Upload a Snapshot:
    This endpoint is used to upload device configurations and network state for analysis.
    POST /networks/<network>/snapshots?snapshot=<snapshot_name>
    Payload: Multipart form-data containing your configuration files.
  3. List Available Networks or Snapshots:
    Retrieve a list of your networks or available snapshots.
    GET /networks
    GET /networks/<network>/snapshots
  4. List Available Questions:
    View which analysis questions can be executed against your snapshot.
    GET /questions
  5. Execute a Question:
    Run a specific network analysis against your uploaded snapshot.
    POST /networks/<network>/snapshots/<snapshot>/questions/<question>
    Payload Example:
    {
      "parameters": { }
    }
        
  6. Retrieve Question Results:
    Fetch the results of your analysis.
    GET /networks/<network>/snapshots/<snapshot>/questions/<question>/answer
  7. Delete a Network or Snapshot (Optional):
    Remove outdated resources.
    DELETE /networks/<network>
    DELETE /networks/<network>/snapshots/<snapshot>

Replace <network>, <snapshot>, and <question> with your own network, snapshot names, and desired question type. All endpoints accept and return JSON unless uploading a snapshot, which uses multipart form data.

Sample Workflow

This section guides you through a typical workflow for using the Batfish REST API to automate network analysis tasks, step by step:

  1. Create a Network:
    Start by creating a new network environment to organize your snapshots and analyses.
    POST /networks
    Content-Type: application/json
    
    {
      "name": "my_network"
    }
        
  2. Upload a Snapshot:
    Next, upload your network configuration files as a snapshot. This provides Batfish the data needed for analysis.
    POST /networks/my_network/snapshots?snapshot=my_snapshot
    Content-Type: multipart/form-data
    
    [Include device config files here]
        
  3. List Available Questions:
    Before running an analysis, check which questions (analysis types) you can execute.
    GET /questions
        
  4. Execute a Question:
    Run a specific analysis query on your snapshot to gather network insights.
    POST /networks/my_network/snapshots/my_snapshot/questions/init_info
    Content-Type: application/json
    
    {
      "parameters": {}
    }
        
  5. Retrieve the Answer:
    Obtain the results of your question execution to review findings.
    GET /networks/my_network/snapshots/my_snapshot/questions/init_info/answer
        

This workflow demonstrates a common pattern for integrating Batfish REST API calls into automation or validation scripts. Adjust the network, snapshot, and question names as needed for your environment.

Payload Format

This section explains the data formats expected and returned when interacting with the Batfish REST API, with step-by-step details:

  1. JSON Format for Requests and Responses:
    Most Batfish REST API endpoints accept and return data formatted as JSON. Ensure your request bodies are properly structured JSON objects or arrays.
    {
      "parameters": {
        "someParameter": "value"
      }
    }
        
  2. Multipart Form-Data for Snapshot Uploads:
    When uploading snapshots, the API requires a multipart form-data payload containing your device configuration files. Each file should be included as a separate part.
    Content-Type: multipart/form-data; boundary=------------------------xyz
    
    --------------------------xyz
    Content-Disposition: form-data; name="file"; filename="config1.cfg"
    Content-Type: text/plain
    
    [contents of config1.cfg]
    
    --------------------------xyz
    Content-Disposition: form-data; name="file"; filename="config2.cfg"
    Content-Type: text/plain
    
    [contents of config2.cfg]
    
    --------------------------xyz--
        
  3. Ensure Proper Content-Type Headers:
    Set the Content-Type header appropriately for each request:
    • Use application/json for JSON payloads
    • Use multipart/form-data and specify the boundary when uploading files
  4. Validate JSON Syntax:
    Before sending requests, verify your JSON is valid using a linter or formatter to avoid request errors.
  5. Response Data:
    API responses will generally be JSON objects. Parse them accordingly in your automation or scripts to extract needed information.

Following these payload format guidelines ensures smooth communication with the Batfish REST API and reduces errors during automation and integration workflows.

Response Codes

This section walks you through the typical HTTP response codes you may encounter while working with the Batfish REST API and what they indicate at each step:

  1. 200 OK:
    The request was successful and the response contains the expected data. Common for retrieval, execution, and status-check endpoints.
  2. 201 Created:
    A resource (such as a new network or snapshot) was successfully created. The response may include information about the new resource.
  3. 400 Bad Request:
    The server could not process the request due to invalid syntax or data. Check the request body for errors or missing fields.
  4. 401 Unauthorized:
    The request lacks valid authentication credentials. Confirm that you have the right token or authorization headers if authentication is enabled.
  5. 403 Forbidden:
    Authentication succeeded but you do not have sufficient permissions to perform the action.
  6. 404 Not Found:
    The requested resource does not exist. Double-check network, snapshot, or question names in the URL.
  7. 500 Internal Server Error:
    An unexpected problem occurred on the server side. If this error persists, review server logs or reach out for support.

Properly handling these response codes can help you quickly detect issues and ensure robust interaction with the Batfish REST API during automation or troubleshooting.

Conclusion

In this post, we explored the comprehensive Batfish REST API, a powerful tool designed to streamline and automate network analysis, validation, and troubleshooting. We walked through the core components that form the API’s foundation, including networks, snapshots, sessions, questions, and answers. Setting up your environment with the necessary prerequisites ensures smooth interaction with the API.

We examined the authentication methods that secure your access and detailed the common endpoints you’ll use to manage networks, upload snapshots, run analyses, and retrieve results. Our sample workflow demonstrated how typical tasks are performed step-by-step, providing a practical blueprint for integrating Batfish into your automation pipelines.

Understanding the expected payload formats and interpreting response codes effectively can help avoid errors and improve the reliability of your network validation processes.

With these insights, you are well-equipped to leverage Batfish’s REST API to enhance your network infrastructure operations, reduce manual effort, and proactively identify configuration issues before they impact your environment.

Thank you for following along! If you have any questions or want to share your experience using Batfish, feel free to reach out or leave a comment. Happy network analyzing!