> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pathstack.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

To use the PathStack API, you must pass a [JWT](https://jwt.io/) access token in the header of each request. This is
for security to ensure no one else can access your data.

## Generating an access token

To get an access token, you need to make a call to the `/token` endpoint and pass your username and password.

<Note>
  Access tokens expire 60 minutes after they are generated. Once an access token has expired you will no longer be able
  to use it and any API calls you try to make will return a **401: JWT has expired** error response with a message that
  the token has expired. You will then either have to generate a new token with the `/token` endpoint, or you can use
  the **Refresh Token** from the original `/token` call to get a new **Access Token**.
</Note>

<CodeGroup>
  ```python Python theme={null}
  import requests

  url = "https://api.pathstack.io/token"

  payload = {
  "username": "username",
  "password": "password"
  }
  headers = {"Content-Type": "application/json"}

  response = requests.request("POST", url, json=payload, headers=headers)

  access_token = response.json()['data']['access_token']
  refresh_token = response.json()['data']['refresh_token']
  ```

  ```javascript JavaScript theme={null}
  const options = {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: '{"username":"<username>","password":"<password>"}'
  };

  fetch('https://api.pathstack.io/token', options)
    .then(response => response.json())
    .then(response => {
      const access_token = response['data']['access_token'];
      const refresh_token = response['data']['refresh_token'];
    })
    .catch(err => console.error(err));
  ```

  ```java Java theme={null}
  import java.net.HttpURLConnection;
  import java.net.URL;
  import java.io.OutputStream;
  import java.util.Scanner;
  import org.json.JSONObject;

  public class TokenRequest {
      public static void main(String[] args) {
          String url = "https://api.pathstack.io/token";
          String payload = "{ \"username\": \"username\", \"password\": \"password\" }";

          HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", "application/json");
          connection.setDoOutput(true);

          try (OutputStream os = connection.getOutputStream()) {
              os.write(payload.getBytes());
          }

          try (Scanner scanner = new Scanner(connection.getInputStream())) {
              String responseBody = scanner.useDelimiter("\\A").next();
              JSONObject jsonResponse = new JSONObject(responseBody);
              String access_token = jsonResponse.getJSONObject("data").getString("access_token");
              String refresh_token = jsonResponse.getJSONObject("data").getString("refresh_token");
          }

          connection.disconnect();
      }
  }
  ```

  ```dotnet .NET theme={null}
  using System;
  using System.IO;
  using System.Net;
  using System.Text;
  using Newtonsoft.Json.Linq;

  class TokenRequest
  {
      static void Main()
      {
          string url = "https://api.pathstack.io/token";
          string payload = "{ \"username\": \"username\", \"password\": \"password\" }";

          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
          request.Method = "POST";
          request.ContentType = "application/json";
          request.ContentLength = payload.Length;

          using (Stream requestStream = request.GetRequestStream())
          using (StreamWriter writer = new StreamWriter(requestStream))
          {
              writer.Write(payload);
          }

          using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
          using (Stream responseStream = response.GetResponseStream())
          using (StreamReader reader = new StreamReader(responseStream))
          {
              string responseBody = reader.ReadToEnd();
              JObject jsonResponse = JObject.Parse(responseBody);
              string access_token = jsonResponse["data"]["access_token"].ToString();
              string refresh_token = jsonResponse["data"]["refresh_token"].ToString();
          }
      }
  }
  ```

  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.pathstack.io/token \
    --header 'Content-Type: application/json' \
    --data '{
    "username": "username",
    "password": "password"
  }'
  ```
</CodeGroup>

This will return a response that looks something like this:

```json JSON theme={null}
{
  "data": {
    "token_type": "Bearer",
    "expires_in": 3600,
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJld2ZlZXdmZmUiLCJuYW1lIjoiSm9obiBEb2UiLCJpYXQiOjE1MTYyMzkwMjJ9.TgSl52RmirkU3f1tYG6E5lK5Ptt1C0_KSOSj9H-WYAQ",
    "sub": "a6caf0bd-dbdf-4dfb-bcab-34f73e4c5b64"
  }
}
```

Now that you have an **Access Token**, you can begin [making requests to the PathStack API](/content/request-data).

## Using a refresh token

To get a new token, you can either authenticate again with your username and password, or you call the `/refresh` endpoint.
The latter option is often preferable since you will not need to store your username and password for later use.

Using the `sub` and the `refresh_token`, you can call the `/refresh` endpoint to get new access and refresh token.

<CodeGroup>
  ```python Python theme={null}
  import requests

  url = "https://api.pathstack.io/refresh"

  payload = {
      "sub": "<your-sub>",
      "refresh_token": "<your-refresh-token>"
  }
  headers = {"Content-Type": "application/json"}

  response = requests.request("POST", url, json=payload, headers=headers)

  access_token = response.json()['data']['access_token']
  refresh_token = response.json()['data']['refresh_token']
  ```

  ```javascript JavaScript theme={null}
  const options = {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: '{"sub":"<your-sub>","refresh_token":"<your-refresh-token>"}'
  };

  fetch('https://api.pathstack.io/refresh', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));
  ```

  ```java Java theme={null}
  import java.io.OutputStream;
  import java.net.HttpURLConnection;
  import java.net.URL;
  import java.nio.charset.StandardCharsets;
  import java.util.Scanner;
  import org.json.JSONObject;

  public class RefreshTokenRequest {
      public static void main(String[] args) {
          String url = "https://api.pathstack.io/refresh";
          String sub = "<your-sub>";
          String refreshToken = "<your-refresh-token>";

          String payload = "{ \"sub\": \"" + sub + "\", \"refresh_token\": \"" + refreshToken + "\" }";
          byte[] postData = payload.getBytes(StandardCharsets.UTF_8);

          HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", "application/json");
          connection.setDoOutput(true);

          try (OutputStream os = connection.getOutputStream()) {
              os.write(postData);
          }

          try (Scanner scanner = new Scanner(connection.getInputStream())) {
              String responseBody = scanner.useDelimiter("\\A").next();
              JSONObject jsonResponse = new JSONObject(responseBody);

              String access_token = jsonResponse.getJSONObject("data").getString("access_token");
              String refresh_token = jsonResponse.getJSONObject("data").getString("refresh_token");

              System.out.println("Access Token: " + access_token);
              System.out.println("Refresh Token: " + refresh_token);
          }

          connection.disconnect();
      }
  }
  ```

  ```dotnet .NET theme={null}
  using System;
  using System.IO;
  using System.Net;
  using System.Text;
  using Newtonsoft.Json.Linq;

  class RefreshTokenRequest
  {
      static void Main()
      {
          string url = "https://api.pathstack.io/refresh";
          string sub = "<your-sub>";
          string refreshToken = "<your-refresh-token>";

          string payload = $"{{ \"sub\": \"{sub}\", \"refresh_token\": \"{refreshToken}\" }}";
          byte[] postData = Encoding.UTF8.GetBytes(payload);

          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
          request.Method = "POST";
          request.ContentType = "application/json";
          request.ContentLength = postData.Length;

          using (Stream requestStream = request.GetRequestStream())
          {
              requestStream.Write(postData, 0, postData.Length);
          }

          using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
          using (Stream responseStream = response.GetResponseStream())
          using (StreamReader reader = new StreamReader(responseStream))
          {
              string responseBody = reader.ReadToEnd();
              JObject jsonResponse = JObject.Parse(responseBody);

              string access_token = jsonResponse["data"]["access_token"].ToString();
              string refresh_token = jsonResponse["data"]["refresh_token"].ToString();

              Console.WriteLine("Access Token: " + access_token);
              Console.WriteLine("Refresh Token: " + refresh_token);
          }
      }
  }
  ```

  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.pathstack.io/refresh \
    --header 'Content-Type: application/json' \
    --data '{
    "sub": "<your-sub>",
    "refresh_token": "<your-refresh-token>"
  }'
  ```
</CodeGroup>
