> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt. For full content including API reference and SDK examples, see https://learning.postman.com/llms-full.txt.

# Generate an OAuth Token

POST https://api.getpostman.com/oauth2/token
Content-Type: application/json

Generates an OAuth 2.0 access token for a client application using the `client_credentials` grant type. Use this endpoint with backend services or bots to authenticate and authorize API requests without user interaction.

**Note:**

This endpoint uses Basic Auth. You must pass a valid client ID and client secret for the username and password, respectively.


Reference: https://learning.postman.com/api-docs/api-reference/o-auth-2-0/generate-oauth-token

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: Postman API
  version: 1.0.0
paths:
  /oauth2/token:
    post:
      operationId: generateOauthToken
      summary: Generate an OAuth Token
      description: >
        Generates an OAuth 2.0 access token for a client application using the
        `client_credentials` grant type. Use this endpoint with backend services
        or bots to authenticate and authorize API requests without user
        interaction.


        **Note:**


        This endpoint uses Basic Auth. You must pass a valid client ID and
        client secret for the username and password, respectively.
      tags:
        - oAuth20
      parameters:
        - name: Authorization
          in: header
          description: Basic authentication
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/generateOauthTokenResponse'
        '400':
          description: Bad Request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/oauthTokenError'
        '404':
          description: Token Not Found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/oauthTokenError'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/generateOauthToken'
servers:
  - url: https://api.getpostman.com
    description: https://api.getpostman.com
  - url: https://api.eu.postman.com
    description: https://api.eu.postman.com
components:
  schemas:
    generateOauthToken:
      type: object
      properties:
        grant_type:
          type: string
          description: The `client_credentials` OAuth grant type.
        installationAuthId:
          type: string
          description: The client's installation authentication ID.
        jwt:
          type: string
          description: >-
            A signed JWT token. The token must include `iss` (issuer), `aud`
            (audience), `iat` (issued at), `exp` (expiration timestamp), and
            `jti` (JWT ID).
      required:
        - grant_type
        - installationAuthId
        - jwt
      title: generateOauthToken
    GenerateOauthTokenResponseTokenType:
      type: string
      enum:
        - Bearer
      description: The `Bearer` token type.
      title: GenerateOauthTokenResponseTokenType
    generateOauthTokenResponse:
      type: object
      properties:
        access_token:
          type: string
          description: A Postman OAuth 2.0 access token.
        expires_in:
          type: integer
          description: The time the token expires, in milliseconds.
        token_type:
          $ref: '#/components/schemas/GenerateOauthTokenResponseTokenType'
          description: The `Bearer` token type.
      title: generateOauthTokenResponse
    oauthTokenError:
      type: object
      properties:
        error:
          type: string
          description: The type of error.
        error_description:
          type: string
          description: Information about the error.
      title: oauthTokenError
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic

```

## Examples

### Successful Response



**Request**

```json
undefined
```

**Response**

```json
{
  "access_token": "PMAK-XXX",
  "expires_in": 3600,
  "token_type": "Bearer"
}
```

**SDK Code**

```python Successful Response
import requests

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

headers = {
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Successful Response
const url = 'https://api.getpostman.com/oauth2/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: undefined
};

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

```go Successful Response
package main

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

func main() {

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

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

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby Successful Response
require 'uri'
require 'net/http'

url = URI("https://api.getpostman.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/json'

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

```java Successful Response
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

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

```php Successful Response
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.getpostman.com/oauth2/token', [
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<username>', '<password>'],
]);

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

```csharp Successful Response
using RestSharp;
using RestSharp.Authenticators;

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

request.AddHeader("Content-Type", "application/json");
IRestResponse response = client.Execute(request);
```

```swift Successful Response
import Foundation

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

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.getpostman.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 an OAuth Token



**Request**

```json
{
  "grant_type": "client_credentials",
  "installationAuthId": "e868878e40f646ce8b5620736995dc89",
  "jwt": "eyJhXXX"
}
```

**Response**

```json
{
  "access_token": "PMAK-XXX",
  "expires_in": 3600,
  "token_type": "Bearer"
}
```

**SDK Code**

```python Generate an OAuth Token
import requests

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

payload = {
    "grant_type": "client_credentials",
    "installationAuthId": "e868878e40f646ce8b5620736995dc89",
    "jwt": "eyJhXXX"
}
headers = {
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Generate an OAuth Token
const url = 'https://api.getpostman.com/oauth2/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: '{"grant_type":"client_credentials","installationAuthId":"e868878e40f646ce8b5620736995dc89","jwt":"eyJhXXX"}'
};

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

```go Generate an OAuth Token
package main

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

func main() {

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

	payload := strings.NewReader("{\n  \"grant_type\": \"client_credentials\",\n  \"installationAuthId\": \"e868878e40f646ce8b5620736995dc89\",\n  \"jwt\": \"eyJhXXX\"\n}")

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

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/json")

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

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

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

}
```

```ruby Generate an OAuth Token
require 'uri'
require 'net/http'

url = URI("https://api.getpostman.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/json'
request.body = "{\n  \"grant_type\": \"client_credentials\",\n  \"installationAuthId\": \"e868878e40f646ce8b5620736995dc89\",\n  \"jwt\": \"eyJhXXX\"\n}"

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

```java Generate an OAuth Token
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.getpostman.com/oauth2/token")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/json")
  .body("{\n  \"grant_type\": \"client_credentials\",\n  \"installationAuthId\": \"e868878e40f646ce8b5620736995dc89\",\n  \"jwt\": \"eyJhXXX\"\n}")
  .asString();
```

```php Generate an OAuth Token
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.getpostman.com/oauth2/token', [
  'body' => '{
  "grant_type": "client_credentials",
  "installationAuthId": "e868878e40f646ce8b5620736995dc89",
  "jwt": "eyJhXXX"
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
    'auth' => ['<username>', '<password>'],
]);

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

```csharp Generate an OAuth Token
using RestSharp;
using RestSharp.Authenticators;

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

request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"grant_type\": \"client_credentials\",\n  \"installationAuthId\": \"e868878e40f646ce8b5620736995dc89\",\n  \"jwt\": \"eyJhXXX\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Generate an OAuth Token
import Foundation

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

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/json"
]
let parameters = [
  "grant_type": "client_credentials",
  "installationAuthId": "e868878e40f646ce8b5620736995dc89",
  "jwt": "eyJhXXX"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

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

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()
```