Twitter API V2 Documentation

OAuth 2.0 Authorization Code Flow with PKCE with example

How to connect to endpoints using OAuth 2.0 Authorization Code Flow with PKCE with example

How long will my credentials stay valid?  

By default, the access token you create through the Authorization Code Flow with PKCE will only stay valid for two hours unless you’ve used the offline.access scope.

How to generate access token with refresh token

Refresh tokens allow an application to obtain a new access token without prompting the user via the refresh token flow.

If the scope offline.access is applied an OAuth 2.0 refresh token will be issued. With this refresh token, you obtain an access token. If this scope is not passed, we will not generate a refresh token.

An example of the request you would make to use a refresh token to obtain a new access token is as follows:

POST 'https://api.twitter.com/2/oauth2/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'refresh_token=bWRWa3gzdnRRcTJ5VUxWX1lZTDdJSUtmaWcxbTVxdEFXcW5tOjE2MjIxNDc3NDM5MTQ6MToxOnJ0OjE' \ --data-urlencode 'grant_type=refresh_token' \ --data-urlencode 'client_id=rG9n6402A3dbUJKzXTNX4oWHJ'

Working with confidential clients

If you are working with confidential clients, you will need to use a basic authentication scheme for generating an authorization header with base64 encoding while making requests to the token endpoints.

The userid and password are separated by a single colon (“:”) character within a base64 encoded string in the credentials.

Note: To create the basic authorization header you will need to base64 encoding on your Client ID and Client Secret

Ex: client_id:client_secret | base64

How to Get Refresh and Access token

Authentication URL

https://twitter.com/i/oauth2/authorize?response_type=code&client_id=Ni03RmlHZFotNlBUUWtljaQ&redirect_uri=https://devopsolution.online&scope=tweet.read%20users.read%20offline.access&state=state&code_challenge=challenge&code_challenge_method=plain

Parameters

To construct an OAuth 2.0 authorisation URL, you will need to ensure you have the following parameters in the authorization URL. 

Parameter

Description

response_type

You will need to specify that this is a code with the word “code”. 

client_id

Can be found in the developer portal under the header “Client ID”.

redirect_uri

Your callback URL. This value must correspond to one of the Callback URLs defined in your App’s settings. For OAuth 2.0, you will need to have exact match validation for your callback URL.

state

A random string you provide to verify against CSRF attacks.  The length of this string can be up to 500 characters.

code_challenge

PKCE parameter, a random secret for each request you make. 

code_challenge_method

Specifies the method you are using to make a request (S256 OR plain).

Auth Basic Code

To create the basic authorization header you will need to base64 encoding on your Client ID and Client Secret

Ex: client_id:client_secret into base64 encoding

basic-access-img1

From Our Side Steps:

Requirements for Authorization URL

  1. Client id available at >> Projects & Apps >> keys and Token
  2. Redirect URL
      • Edit User Authentication settings
      • Copy redirect URI

Note: Show App only for Demonstration Purpose only and all the Credentials will be deleted after the documentation.

  1. URL
https://twitter.com/i/oauth2/authorize?response_type=code&client_id=Enter client_id here&redirect_uri=Enter_Redirect_URI_HERE&scope=tweet.read%20users.read%20offline.access&state=state&code_challenge=challenge&code_challenge_method=plain

By Replace these two Parts

  1. Enter the URL in Browser to Get Auth code
  2. Twitter will redirect to login and if you are already login then Authentication Page, Click Authorize APP
  1. It will Redirect to Redirect URI which has been Provided inside the URL.
  2. Copy the Code part from redirect page URL

SprigHub:https://twitter.com/i/oauth2/authorize?response_type=code&client_id=MkhNOGNKUThza18xepjaQ&scope=tweet.read%20users.read%20offline.access&state=state&redirect_uri=http%3A%2F%2Flocalhost%3A2000%2Fsettings%2Ftwitter-ads-app-verification&code_challenge_method=plain&code_challenge=challenge

  1. Python code to generate refresh token from authentication code
import requests

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization' : 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx==',
    }

data = {
    'code': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'grant_type': 'authorization_code',
    'client_id': client_id_company,
    'redirect_uri': 'http://localhost:2000/settings/',
    'code_verifier': 'challenge'
}

response = requests.post('https://api.twitter.com/2/oauth2/token', headers=headers, data=data).json()
print(response)
  1. Python code to generate refresh-token and authentication code from refresh-token.
import requests

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': Authrization_basic_company,
}

data = {
    'refresh_token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'grant_type': 'refresh_token',
    'client_id': client_id_company,
}

response = requests.post('https://api.twitter.com/2/oauth2/token', headers=headers, data=data).json()
print(response)
  1. Using access token to access Data from API
import requests

headers = {
    
    'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx',
}

params = {
    'start_time': '2022-12-30T04:04:22.000Z',
    'end_time': '2023-01-03T11:13:52.000Z',
    'tweet.fields': 'organic_metrics,non_public_metrics,id',
}

response = requests.get('https://api.twitter.com/2/users/{id}/tweets', params=params, headers=headers).json()
print(response)

Note:

  1. The access token will expire in 2 hours
  2. Refresh token can generate access token multiple time but refresh token change
      • Every time when we use the refresh token to generate an access token we will get new access and a new refresh token
      • New refresh token need to be update in database every time when we use it for access token.
  3. 30 days rule for non-public and organic data for metrics
  1. Columns for metrics

Non-Public-Metrics

  1. Impressions
  2. Retweets
  3. Likes
  4. Replies
  5. URL Link Clicks
  6. User Profile Clicks
  7. Video views
  8. Video view quartiles

Also Available in Public-Metrics

  1. Retweets
  2. Quote Tweets
  3. Likes
  4. Replies
  5. Video views

Note: When using Twitter Public Metrics Using the public metrics field, will return the total count of Retweets from both organic and paid contexts, in order to maintain consistency with the counts shown publicly on Twitter.

Request in Postman Lookalike

Docs Eng
Engineer at SprigHub
Cookie Value: