There is a convenient API for handling Qiita called Qiita API. https://qiita.com/api/v2/docs
Here is a sample to try using this with Django.
Only Oauth is dealt with in this article (otherwise it's just a request)
Register the application from the following URL. https://qiita.com/settings/applications
You will get a Client ID
and a Client Secret
.
GET /api/v2/oauth/authorize
Display the authorization screen for the user.
If approved by the user, code
will be added to the Callback URL specified in the application registration above.
In addition, specify scope
and state
with parameters.
Regarding the scope, here
state is that you can specify the value included in the query of the URL to redirect for CSRF countermeasures.
python
state = random.randint(1,100000)
request.session['qiita_state'] = state
return redirect(QIITA_OAUTH_URL + '?client_id=' + QIITA_CLIENT_ID + '&state=' + str(state) + '&scope=read_qiita+write_qiita')
Since state
is meaningless unless it is a random value, it is randomly generated and saved in the session.
POST /api/v2/access_tokens
Now you have an access token.
Use the code
you got from GET / api / v2 / oauth / authorize
earlier.
At the same time, use the client_id
and client_secret
obtained by registering the application.
python
@csrf_exempt
def qiita_oauth(request):
if request.method == 'GET':
state = request.session['qiita_state']
if state == int(request.GET.get("state")):
if "code" in request.GET:
code = request.GET.get("code")
body = {
'client_id': QIITA_CLIENT_ID,
'client_secret': QIITA_CLIENT_SECRET,
'code': code
}
header = {
'Content-Type': 'application/json',
}
req = urllib.request.Request(QIITA_ACCESSTOKEN_URL, json.dumps(body).encode(), header)
try:
with urllib.request.urlopen(req) as res:
#Post-success processing
except urllib.error.HTTPError as err:
#Processing after request failure
except urllib.error.URLError as err:
#Processing after request failure
else:
#processing after state authentication failure
ʻIf state == int (request.GET.get ("state")): `checks if the state is correct.
Recommended Posts