Fyers API V2 - Auth code and Token generation procedure

from urllib.parse import urlparse, parse_qs
import requests
from fyers_api import fyersModel
from fyers_api import accessToken
import traceback
import json

# FILL YOU DETAILS IN BELOW HIGHLIGHTED FIELDS

client_id = ""
secret_key = ""
redirect_uri = "http://localhost:8080"
response_type = "code"
grant_type = "authorization_code"
state = "None"
nonce = "private"

input = {"fyers_id":"","password":"","pan_dob":"","app_id":"","redirect_uri":"http://localhost:8080","appType":"100","code_challenge":"","state":"None","scope":"","nonce":"","response_type":"code","create_cookie":True}

session = session=accessToken.SessionModel(client_id=client_id,
secret_key='',redirect_uri='http://localhost:8080',
response_type='code', grant_type='authorization_code',state= None )
response = session.generate_authcode()
print("Response from Try-Catch 1 is - \n", response)

headers = {
"accept": "*/*",
"accept-language": "en-IN,en-US;q=0.9,en;q=0.8",
"content-type": "application/json; charset=UTF-8",
"sec-ch-ua" :'"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
}

result = requests.post("https://api.fyers.in/api/v2/token",
headers=headers, json=input, allow_redirects=True)
var = json.loads(result.content)
URL = var["Url"]
print(URL)
parsed = urlparse(URL)
parsedlist = parse_qs(parsed.query)['auth_code']
auth_code = parsedlist[0]
session.set_token(auth_code)
response = session.generate_token()
access_token = response["access_token"]
print(access_token)

fyers = fyersModel.FyersModel(client_id=client_id, token=access_token,log_path="xxxx")

print(fyers.get_profile())

data = {"symbol":"NSE:SBIN-EQ","resolution":"1","date_format":"0","range_from":"1629695667","range_to":"1629710067","cont_flag":"1"}

print(fyers.history(data))

print(fyers.orderbook())

Hi Ganesh,

Thanks for that snippet, when I fill up details and execute this code I get error as shown below:

KeyError: ‘Url’

and when I print URL I get following response as shown below:

** {‘appName’: ‘Test’, ‘image’: None, ‘app_id’: ‘XXXXXXXXX’, ‘user_id’: ‘XXXXX’, ‘redirectUrl’: ‘http://localhost:8080’, ‘permissions’: [‘x:2’], ‘auth’: ‘eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkuWnllcnMuaW4iLCJpYXQiOjE2Mjk4OTUyNDQsImV4cCI6MTYyOTg5NTU0NCwibmJmIjoxNjI5ODk1MjQ0LCJhdWQiOiJbXCJ4OjJcIiwgXCJ4OjFcIiwgXCJ4OjBcIl0iLCJzdWIiOiXhY2Nlc3NfdG9rZW4iLCJhdF9oYXNoIjoiZ0FBQUFBQmhKanBNMzJ3NllQNnlhd3dYT0VFMmRoOFlId05lRi1QSXRuV19odE45Wnpud0FMMllqSm5BdHZlcDNzc0RxbUVzSHV3RW9Gd21wSGdxa3ZiNjJ5YmUzQjRpSEGkR2RpX0ZPQ1dOYjJ4Y01DQ1hGR2s9IiwiZGlzcGxheV9uYW1lIjoiRkEwNjE3In0.05Kuh_quJwKI91WJSiYF8MKAjFelRL42EoLulT8BQ0U’, ‘response_type’: ‘code’, ‘scope’: ‘’, ‘nonce’: ‘’, ‘state’: ‘None’}**

so here we want to use “auth” to set in session as auth_code? Am I correct here?

Regards,

Amit

**this code error **

File “c:\Users\User\Desktop\FYR[fy.py](http://fy.py)”, line 38, in

URL = var[“Url”]

KeyError: ‘Url’

Dear sir

if possible please make video on this in detail

If anyone needs the code refer this: https://github.com/tkanhe/Fyers-API-Access-Token-Generation-V2

Is there any Postman/REST API version of this example?

ok finally after lot of trial and error and playing with Python, I made this work from my Java code.

But @tejas_khoday I don’t see the https://api.fyers.in/api/v2/token API publicly documented on https://myapi.fyers.in/docs/#section/Introduction or in Postman dump.

Am I missing anything? I am not comfortable using an undocumented API as Fyres team can take it off anytime or bring in a breaking behavior.

Ideally there should be pure API way of generating token as otherwise I cant completely automate the trading and defeats the purpose. Especially in my case I keep travelling and sometimes its not possible to login through manual means.

You get full credit… thanks buddy

Is token API broken today after the update? Anybody facing the issue?

Yes. Its broken. Funny thing is that fyers team is asking to reload the browser to get this resolved (API authentication). They also closed my ticket assuming that the issue is resolved. What a wonderful support team you are @tejas_khoday @P5riXHjRDF

This was the funny reply from them regarding an API related issue.

Greetings from FYERS!
Kindly do a hard re-load using this key’s CTRL + SHIFT + R.
We consider your issue to be addressed and resolved, hence we are closing the ticket.

I made the changes yesteday, you can check it out at https://github.com/tkanhe/Fyers-API-Access-Token-Generation-V2

Thanks, will check this out but still today’s trade opportunities lost thanks to disruptive changes without notice. I am seriously thinking of going back to Angel SmartAPIs.

Thanks, will check this out but still today’s trade opportunities lost thanks to disruptive changes without notice. I am seriously thinking of going back to Angel SmartAPIs.

@sujith - This is concerning to hear. Kindly share the ticket ID here. We will get it checked by. We will look into it and get it checked. Regret the inconvenience caused!

Are you using a mix of v1 and v2 APIs? If yes, is that a right approach?

@P5riXHjRDF Here is the ticket - 611798

can you please confirm if the token API is an official API? Can we use it in our automated trading?

@eZkU72tBev No v2 only. I only find what requests are being made and their payload data and then automated it.

The file NEW Fyers Access Token.py I am looking at has following API calls.

Following look v1 APIs:

https://api.fyers.in/vagator/v1/login

https://api.fyers.in/vagator/v1/verify_pin

While the below one is v2:

https://api.fyers.in/api/v2/token

Am I looking at the right file?

@eZkU72tBev yes

ok thanks for prompt reply. Let me use this approach to quickly fix my fyers auto trading code till I make a switch over to SmartAPI