> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://en.megaport.ferndocs.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://en.megaport.ferndocs.com/_mcp/server.

# Generate Access Token - Staging

POST https://api.megaport.com/oauth2/token
Content-Type: application/x-www-form-urlencoded

Generates an access token with an API key in the Staging environment.

After you have created an API key in the Portal, consisting of a client ID and client secret, you can generate an access token (JWT) for authorization of Megaport APIs. JWTs are short lived and the expiry time is set when you create the API key in the Portal (between 5 minutes and 24 hours). The expiry can be seen in the response of this endpoint, and is represented in seconds.

**Tip:** You can use the [https://jwt.io/](https://jwt.io/) site to learn more about and verify the access token. Copy the access token (JWT) into the Encoded box, it will display decoded information about the token. For example, in the Payload Data, the `iat` value indicates when the token was issued (seconds since Unix epoch) and the `exp` value indicates when the token expires.

The request URL that you need to use depends on the environment in which you are generating an access token. In the **Staging** environment, this request URL should be used:

* [https://auth-m2m-staging.megaport.com/oauth2/token](https://auth-m2m-staging.megaport.com/oauth2/token)

For more details on environments, see [Environments](https://dev.megaport.com/#environments).

Provide values for these parameters in the Authorization tab of the call:

* `Username` â€“ The client ID that you copied when creating the API key.

* `Password` â€“ The client secret that you copied when creating the API key.

**Note:** These parameters contain sensitive data. If you are working in a collaborative environment, you might want to set the client ID and client secret as the variables \{\{apiKeyClientId}} and \{\{apiKeyClientSecret}} respectively.

In the Body tab, set the Body coding format to `x-www-form-urlencoded`, and enter a key called *grant\_type* which is set to a value of *client\_credentials*.

### **Using the access token**

After you successfully generate an access token, you will see these values in the response:

* `access_token` - The access token (JWT).

* `expires_in` - The expiry of the token, measured in seconds. For example, if the expiry was set to 24 hours in the API key, this value would be 86400 (seconds). If the expiry was set to 5 minutes, then this value would be 300.

* `token_type` - Bearer

Copy the access token from the response.

You can create a new variable for the access token, ensuring that you copy the access token into the CURRENT VALUE field of the variable entry. For example, call the new variable \{\{access\_token}}.

For each API call that you need to send, in the Authorization tab, the Type should be set to Bearer Token and the Token should be set to the access token variable \{\{access\_token}}.

Reference: https://en.megaport.ferndocs.com/api-reference/megaport-authentication-api-keys/generate-access-token-staging

## Authentication

- `Authorization` header (basic auth, required) — Basic authentication of the form `Basic <base64(username:password)>`.

## Servers

- `https://api.megaport.com` (Production environment, default)
- `https://api-staging.megaport.com` (Staging environment (test only, reset every 24 hours))

## Request

### Body (application/x-www-form-urlencoded)

This endpoint expects an object.

- `grant_type` (string, optional)

## Response

### 200

Generate Access Token - Staging / Generate Access Token - Staging / Generate Access Token - Production / Generate Access Token - Production

- `access_token` (string, optional)
- `expires_in` (double, optional)
- `token_type` (string, optional)

## Examples

### Generate Access Token - Production

**Request**

```json
{
  "grant_type": "client_credentials"
}
```

**Response**

```json
{
  "access_token": "eyJrbWQiOiIzZWhmUjhpbzd5R0pCYnBISWswbHU2d3V6ZzdtYWRcL1VWTjBTbm9XZVE3ND0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsbjd0ZjR1Z2FtwTN1M29sNHU5amE2MjNwIiwidG9rZW5fdXNlIjoiYWNjZXNzIiwic2NvcGUiOiJodHRwczpcL1wvYXBpLXN0YWdpbmcubWVnYXBvcnQuY29tXC9jb21wYW55QWRtaW4iLCJhdXRoX3RpbWUiOjE3MDA2NDExMjcsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvxWlkcC5hcC1zb4V0aGVhc3QtMi5hbWF6b25hd3MuY29tXC9hcC1zb3V0aGVhc3QtMl9LbEh4TTlJUWoiLCJleHAiOjE3MDA3Mjc1MjcsImlhdCI6MTcwMDY0MTEyNywidmVyc2lvbiI6MiwianRpIjoiNzBkNGY1NzAtZWMwNS00NjM0LWFjOTktODJhY2MzNDE2ZThlIiwiY2xpZWg0X2lkIjoibG43dGY0dWdhbWUzdTNvbDR1OWphNjIzcCJ8.XIaEJBmkW3NnBZVrkpmR0u70UO_2MRONAhwtzDo7ql--R1ImWkUVA2ykEmi4eFMJXLzLewW4AQC-A9DC9EJAK2HwS7993ti-OMahfm1BI_0EqXPw-g_GpIulkUd3hTbu1_QifvfYzj3cxP5KxVULj76Xm2w1rKRw5pXdCcU4Y8n_qVlHy6sBYDjtzsKSfd6cBIRMHe-LnNWBLoHdS-tCPeDSMLqzq85MHKMCNt-KQGeuvTKU6PGaJSK1UXRHc5JivoJSeyuc-3vIXmq60fu0CwC0eVhOzkTWh6YUvBylDwYR50gYRfsMUIBbKGyQBP3sPQ2XQZrHMXodTLSKZG-khQ",
  "expires_in": 86400,
  "token_type": "Bearer"
}
```

**SDK Code**

```python Generate Access Token - Production
import requests

url = "https://api.megaport.com/oauth2/token"

payload = ""
headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.post(url, data=payload, headers=headers, auth=("<username>", "<password>"))

print(response.json())
```

```javascript Generate Access Token - Production
const url = 'https://api.megaport.com/oauth2/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams('')
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Generate Access Token - Production
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://api.megaport.com/oauth2/token"

	req, _ := http.NewRequest("POST", url, nil)

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Generate Access Token - Production
require 'uri'
require 'net/http'

url = URI("https://api.megaport.com/oauth2/token")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request.basic_auth("<username>", "<password>")
request["Content-Type"] = 'application/x-www-form-urlencoded'

response = http.request(request)
puts response.read_body
```

```java Generate Access Token - Production
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.megaport.com/oauth2/token")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .asString();
```

```php Generate Access Token - Production
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.megaport.com/oauth2/token', [
  'form_params' => null,
  'headers' => [
    'Content-Type' => 'application/x-www-form-urlencoded',
  ],
    'auth' => ['<username>', '<password>'],
]);

echo $response->getBody();
```

```csharp Generate Access Token - Production
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.megaport.com/oauth2/token");
client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
```

```swift Generate Access Token - Production
import Foundation

let credentials = Data("<username>:<password>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/x-www-form-urlencoded"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.megaport.com/oauth2/token")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Generate Access Token - Staging

**Request**

```json
{
  "grant_type": "client_credentials"
}
```

**Response**

```json
{
  "access_token": "eyJrbWQiOiIzZWhmUjhpbzd5R0pCYnBISWswbHU2d3V6ZzdtYWRcL1VWTjBTbm9XZVE3ND0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsbjd0ZjR1Z2FtwTN1M29sNHU5amE2MjNwIiwidG9rZW5fdXNlIjoiYWNjZXNzIiwic2NvcGUiOiJodHRwczpcL1wvYXBpLXN0YWdpbmcubWVnYXBvcnQuY29tXC9jb21wYW55QWRtaW4iLCJhdXRoX3RpbWUiOjE3MDA2NDExMjcsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvxWlkcC5hcC1zb4V0aGVhc3QtMi5hbWF6b25hd3MuY29tXC9hcC1zb3V0aGVhc3QtMl9LbEh4TTlJUWoiLCJleHAiOjE3MDA3Mjc1MjcsImlhdCI6MTcwMDY0MTEyNywidmVyc2lvbiI6MiwianRpIjoiNzBkNGY1NzAtZWMwNS00NjM0LWFjOTktODJhY2MzNDE2ZThlIiwiY2xpZWg0X2lkIjoibG43dGY0dWdhbWUzdTNvbDR1OWphNjIzcCJ8.XIaEJBmkW3NnBZVrkpmR0u70UO_2MRONAhwtzDo7ql--R1ImWkUVA2ykEmi4eFMJXLzLewW4AQC-A9DC9EJAK2HwS7993ti-OMahfm1BI_0EqXPw-g_GpIulkUd3hTbu1_QifvfYzj3cxP5KxVULj76Xm2w1rKRw5pXdCcU4Y8n_qVlHy6sBYDjtzsKSfd6cBIRMHe-LnNWBLoHdS-tCPeDSMLqzq85MHKMCNt-KQGeuvTKU6PGaJSK1UXRHc5JivoJSeyuc-3vIXmq60fu0CwC0eVhOzkTWh6YUvBylDwYR50gYRfsMUIBbKGyQBP3sPQ2XQZrHMXodTLSKZG-khQ",
  "expires_in": 86400,
  "token_type": "Bearer"
}
```

**SDK Code**

```python Generate Access Token - Staging
import requests

url = "https://api.megaport.com/oauth2/token"

payload = ""
headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.post(url, data=payload, headers=headers, auth=("<username>", "<password>"))

print(response.json())
```

```javascript Generate Access Token - Staging
const url = 'https://api.megaport.com/oauth2/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams('')
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Generate Access Token - Staging
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://api.megaport.com/oauth2/token"

	req, _ := http.NewRequest("POST", url, nil)

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Generate Access Token - Staging
require 'uri'
require 'net/http'

url = URI("https://api.megaport.com/oauth2/token")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request.basic_auth("<username>", "<password>")
request["Content-Type"] = 'application/x-www-form-urlencoded'

response = http.request(request)
puts response.read_body
```

```java Generate Access Token - Staging
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.megaport.com/oauth2/token")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .asString();
```

```php Generate Access Token - Staging
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.megaport.com/oauth2/token', [
  'form_params' => null,
  'headers' => [
    'Content-Type' => 'application/x-www-form-urlencoded',
  ],
    'auth' => ['<username>', '<password>'],
]);

echo $response->getBody();
```

```csharp Generate Access Token - Staging
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.megaport.com/oauth2/token");
client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
```

```swift Generate Access Token - Staging
import Foundation

let credentials = Data("<username>:<password>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/x-www-form-urlencoded"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.megaport.com/oauth2/token")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```