Getting started overview

Getting started with the GraphHopper API involves a sequence of steps designed to enable developers to quickly integrate its geospatial services into their applications. This guide covers account creation, API key retrieval, and making a foundational API call, specifically for routing. GraphHopper provides services such as route planning, geocoding, and matrix calculations, which are accessible via RESTful APIs.

The primary method for interaction is through HTTP requests, typically using cURL for initial testing, or language-specific SDKs and client libraries for more complex integrations. GraphHopper offers official SDKs for Java and JavaScript development, alongside examples for other languages like Python.

To ensure a smooth onboarding process, this guide outlines the necessary steps:

  1. Account Creation: Register for a GraphHopper account to access the dashboard and API key generation.
  2. API Key Retrieval: Locate and copy your unique API key, essential for authenticating all API requests.
  3. First API Request: Construct and execute a basic routing request to verify your setup and API key functionality.

This structured approach aims to provide a clear path from initial setup to a successful first interaction with the GraphHopper API.

Quick reference table

Step What to Do Where
1. Sign Up Create a new GraphHopper account. GraphHopper Registration Page
2. Get API Key Locate and copy your API key from the dashboard. GraphHopper Dashboard: API Keys
3. Make Request Execute a cURL command or use an SDK to call an API endpoint. Your terminal or preferred development environment
4. Review Docs Consult the API reference for specific endpoint details and parameters. GraphHopper Routing API Reference

Create an account and get keys

Accessing the GraphHopper API requires an API key, which is generated upon account creation. This key authenticates your requests and links them to your usage plan, including the free Starter tier. Follow these steps to create an account and obtain your API key:

  1. Navigate to the Registration Page: Open your web browser and go to the official GraphHopper registration portal.

  2. Complete Registration: Fill in the required fields, including your email address and a strong password. You may also need to agree to terms of service and privacy policies. GraphHopper is GDPR compliant, which may involve specific data handling agreements.

  3. Verify Email (if prompted): Some registration processes include an email verification step. Check your inbox for a verification link and click it to activate your account.

  4. Access the Dashboard: Once registered and logged in, you will be directed to your GraphHopper dashboard.

  5. Locate API Keys: Within the dashboard, find the section labeled "API Keys" or "My API Keys." This is typically accessible from the main navigation or a dedicated settings area. The direct link is often https://www.graphhopper.com/dashboard/#/api-keys.

  6. Copy Your API Key: Your unique API key will be displayed. Copy this key and store it securely. This key acts as a credential for all your API requests.

It's important to keep your API key confidential to prevent unauthorized usage of your account and API quota. For production applications, consider using environment variables or a secret management system to handle API keys rather than embedding them directly in your code.

Your first request

After obtaining your API key, you can make your first request to a GraphHopper API endpoint. A common starting point is the Routing API, which calculates directions between two or more points. This example demonstrates how to get a simple route using cURL, a command-line tool for making HTTP requests, and then provides a JavaScript example.

Using cURL

The cURL utility is pre-installed on most Unix-like operating systems and is available for Windows. It provides a straightforward way to test API endpoints without writing code.

Example: Simple Routing Request

This request calculates a route from Berlin, Germany (52.5186, 13.4082) to Hamburg, Germany (53.5511, 9.9937) for a car profile. Replace YOUR_API_KEY with the key you obtained from your GraphHopper dashboard.

curl "https://graphhopper.com/api/1/route?point=52.5186%2C13.4082&point=53.5511%2C9.9937&vehicle=car&key=YOUR_API_KEY"

Expected Output (truncated for brevity):

{
  "hints": {
    "info": {
      "copyrights": [
        "GraphHopper",
        "OpenStreetMap contributors"
      ]
    }
  },
  "paths": [
    {
      "distance": 288863.385,
      "weight": 9726.04,
      "time": 9726044,
      "transfers": 0,
      "points_encoded": true,
      "bbox": [
        9.993701, 
        52.518635, 
        13.408169, 
        53.551079
      ],
      "points": {
        "type": "LineString",
        "coordinates": [
          [13.408169, 52.518635], 
          ...
        ]
      },
      "snapped_waypoints": {
        "type": "PointCollection",
        "coordinates": [
          [13.408169, 52.518635], 
          [9.993701, 53.551079]
        ]
      },
      "instructions": [
        {
          "distance": 0.0,
          "time": 0,
          "sign": 0,
          "text": "Continue straight",
          "interval": [0, 0]
        },
        ...
      ]
    }
  ]
}

This JSON response contains details about the calculated route, including distance, estimated travel time, the encoded polyline representing the path, and turn-by-turn instructions.

Using JavaScript

For web applications, you can use JavaScript with the native fetch API or a library like Axios. This example demonstrates a basic routing request in a browser environment.

const apiKey = 'YOUR_API_KEY';
const point1 = '52.5186,13.4082'; // Berlin
const point2 = '53.5511,9.9937'; // Hamburg
const vehicle = 'car';

const url = `https://graphhopper.com/api/1/route?point=${point1}&point=${point2}&vehicle=${vehicle}&key=${apiKey}`;

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log('Route data:', data);
    // Process the route data, e.g., display on a map
    if (data.paths && data.paths.length > 0) {
      console.log('Distance:', data.paths[0].distance, 'meters');
      console.log('Time:', data.paths[0].time, 'milliseconds');
    }
  })
  .catch(error => {
    console.error('Error fetching route:', error);
  });

When running this JavaScript code in a browser, ensure that you have configured appropriate Cross-Origin Resource Sharing (CORS) policies if making requests from a different domain than GraphHopper's API endpoint. For server-side JavaScript (Node.js), you might use a library like node-fetch or axios.

Common next steps

Once you have successfully made your first GraphHopper API request, consider these common next steps to further integrate and optimize your usage:

  1. Explore Other APIs: GraphHopper offers a range of APIs beyond basic routing. Investigate the Matrix API for calculating travel times and distances between multiple origins and destinations, the Geocoding API for converting addresses to coordinates and vice-versa, or the Route Optimization API for complex logistics problems like the Traveling Salesperson Problem.

  2. Integrate SDKs or Client Libraries: For more robust application development, leverage the official Java or JavaScript SDKs. These libraries often simplify API interaction by handling request construction, response parsing, and error handling. For other languages, consider community-contributed client libraries or build your own wrapper around the REST API.

  3. Implement Error Handling: Develop robust error handling in your application. The GraphHopper API returns specific HTTP status codes and JSON error messages for different issues (e.g., invalid parameters, rate limits, authentication failures). Refer to the GraphHopper API error documentation to understand common error types and how to respond to them programmatically.

  4. Manage API Key Security: Review best practices for securing your API key. Avoid hardcoding it directly into client-side code. For web applications, consider using a backend proxy to make API calls or securely store the key in environment variables for server-side applications.

  5. Monitor Usage and Upgrade Plan: Keep track of your API usage through your GraphHopper dashboard. If your application's needs exceed the free tier limits (2,500 requests/day, 10,000 requests/month), consider upgrading to a paid plan to avoid service interruptions.

  6. Visualize Results: Integrate a mapping library (e.g., Leaflet, OpenLayers, Mapbox GL JS) to visualize the routes and other geospatial data returned by GraphHopper. This enhances the user experience for navigation or logistics applications.

  7. Explore Advanced Parameters: The Routing API, for example, supports numerous parameters to refine route calculations, such as specifying road types to avoid, optimizing for shortest vs. fastest routes, or requesting elevation data. Consult the Routing API reference for a full list of available options.

Troubleshooting the first call

When making your first GraphHopper API call, you might encounter issues. Here's a guide to common problems and their solutions:

  1. Invalid API Key (HTTP 401 Unauthorized):

    • Symptom: The API returns an HTTP 401 status code or a message indicating an invalid key.
    • Solution: Double-check that you have copied your API key correctly from the GraphHopper dashboard. Ensure there are no leading or trailing spaces. Verify that the key is included as a query parameter (?key=YOUR_API_KEY) in your URL.
  2. Bad Request / Invalid Parameters (HTTP 400 Bad Request):

    • Symptom: The API returns an HTTP 400 status code, often with a JSON error message detailing the specific validation failure.
    • Solution: Review your request parameters against the GraphHopper API documentation. Common issues include incorrect coordinate formats (e.g., latitude,longitude vs. longitude,latitude), missing required parameters (like point), or invalid values for parameters (e.g., a non-existent vehicle type). Ensure URL encoding for special characters.
  3. Rate Limit Exceeded (HTTP 429 Too Many Requests):

    • Symptom: The API responds with an HTTP 429 status code.
    • Solution: This indicates you have exceeded the request limits for your current plan (e.g., 2,500 requests/day for the free tier). Wait for the rate limit to reset, or consider upgrading your plan if you require higher usage. Implement exponential backoff in your application to handle rate limits gracefully.
  4. CORS Issues (Browser-specific):

    • Symptom: In a web browser, you might see errors like "Access to fetch at '...' from origin '...' has been blocked by CORS policy."
    • Solution: GraphHopper's API generally supports CORS. Ensure your API key is correctly configured and that your browser is not blocking the request for other reasons (e.g., ad blockers). If making requests from a client-side application to a different domain, the browser enforces CORS. For production, consider using a backend proxy to make API requests, which bypasses client-side CORS restrictions.
  5. Network Connectivity Issues:

    • Symptom: No response from the API, or a network error message from your client (cURL, browser, SDK).
    • Solution: Check your internet connection. Verify that the API endpoint URL (https://graphhopper.com/api/1/route) is correct and accessible. Temporarily disable any firewalls or VPNs that might be blocking outbound connections to external APIs.
  6. Incorrect Endpoint or HTTP Method:

    • Symptom: The API returns an HTTP 404 Not Found or HTTP 405 Method Not Allowed error.
    • Solution: Confirm that you are using the correct API endpoint URL and the appropriate HTTP method (e.g., GET for routing requests) as specified in the GraphHopper API reference.

Always consult the GraphHopper official documentation for the most up-to-date information on error codes and best practices.