Get the number of views of Qiita

at first

In acquiring the number of LGTM and View of Qiita I was able to refer to it because the API specifications have changed, so I couldn't get it. I will describe the acquisition method.

environment

Go 1.15.2

  1. Get an access token === Get token from User Management Screen image.png

Select read_qiita and write_qiita as the scope image.png

  1. Check the URL of the information you want to get === Check the URL of the information you want to get from Official Document. The following two types will be used this time.
GET /api/v2/authenticated_user/items
Returns a list of articles for authenticated users in descending order of creation date and time.
GET /api/v2/items/:item_id
Get the article.
  1. Create a struct to convert json === Since the information returned when hitting the API from the official document is returned in Json, Create a struct that handles the returned data.

UserInfo.go


package data

type UserInfo struct {
	Id               string `json:"id"`
	Likes_count      int    `json:"likes_count"`
	Title            string `json:"title"`
	Page_views_count int    `json:"page_views_count"`
}
  1. Hit the Qiita API ===

web.go


package qiita

import (
	"../data"
	"../exporter"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func GetQiitaViews() {                                      // main.Call from go
	url := "https://qiita.com/api/v2/authenticated_user/items?page=1&per_page=20"
	resp, err := doHttpRequest(url)
	defer resp.Body.Close()                                 //Close Body

	body, err := ioutil.ReadAll(resp.Body)                  //Get from the body of the response

	var userInfos []data.UserInfo
	if err = json.Unmarshal(body, &userInfos); err != nil { //Read json
		return
	}

	index := 0
	for _, user := range userInfos {                       //Read one article at a time
		url = "https://qiita.com/api/v2/items/" + user.Id  //Get the number of views using the article ID
		resp, err := doHttpRequest(url)
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)

		if err := json.Unmarshal(body, &user); err != nil {return}
		userInfos[index].Page_views_count = user.Page_views_count
		index += 1
	}
	exporter.ToCsv(userInfos)                                //csv conversion
}

func doHttpRequest(url string) (*http.Response, error) {     //Common request
	req, _ := http.NewRequest("GET", url, nil)

	buf, _ := ioutil.ReadFile("token.txt")
	token := string(buf)                                     //Manage tokens in a separate file

	req.Header.Set("content-type", "application/json")       //Application in header/Specify json
	req.Header.Set("Authorization", "Bearer " + token)       //Specify token in the header

	client := new(http.Client)
	resp, err := client.Do(req)
	return resp, err
}

It seems that it can not be obtained only with the following API, At first I didn't realize that I needed to query the URL and couldn't get it. Also, since page_view_count returns null (0 when put in struct with Go), It seems that the number of views needs to be obtained for each article. [[Qiita API] Like! I referred to the article of "Automatic counting of views" (https://qiita.com/Naoto9282/items/252c4b386aeafc0052ba).

GET /api/v2/authenticated_user/items
Returns a list of articles for authenticated users in descending order of creation date and time.

Therefore, the following API is used.

GET /api/v2/items/:item_id
Get the article.
  1. CSV output ===

export.go


package exporter

import (
	"../data"
	"encoding/csv"
	"os"
	"strconv"
)

func ToCsv(userInfos []data.UserInfo) {
	file, _ := os.OpenFile("result.csv", os.O_WRONLY|os.O_CREATE, 0600)  //Open file
	defer file.Close()

	writer := csv.NewWriter(file)
	writer.Write([]string{"title", "like_count", "page_views_count"})   //Add a header
	for _, user := range userInfos {
		likesCount := strconv.Itoa(user.Likes_count)                    //Convert int to string
		pageViewsCount := strconv.Itoa(user.Page_views_count)
		writer.Write([]string{user.Title, likesCount, pageViewsCount})  //writing
	}
	writer.Flush()
}

Finally

The source can be found here (https://github.com/kurramkurram/QiitaViewCounts). Due to uploading the source to GitHub, token information is managed in a separate file in the same directory as main.go. Some error handling is omitted.

References

Official [Qiita API] Like! Automatic counting of views Export CSV in Go language! SJIS version for Excel! Go's import cycle not allowed

Recommended Posts

Get the number of views of Qiita
Get the number of digits
Get the number of Youtube subscribers
[Python] Get the number of views of all posted articles
Get the number of PVs of Qiita articles you posted with API
Get the number of articles accessed and likes with Qiita API + Python
10. Counting the number of lines
Calculate the number of changes
How to get the number of digits in Python
Get the size (number of elements) of UnionFind in Python
Calculation of the number of Klamer correlations
Get the number of specific elements in a python list
Get the attributes of an object
Get the first element of queryset
Get the number of occurrences for each element in the list
I checked the distribution of the number of video views of "Flag-chan!" [Python] [Graph]
Get the number of readers of a treatise on Mendeley in Python
Count / verify the number of method calls.
Get the column list & data list of CASTable
Get the minutes of the Diet via API
Get the value of the middle layer of NN
Get the last day of the specified month
[Python] Get the character code of the file
Get the filename of a directory (glob)
[PowerShell] Get the reading of the character string
Count the number of characters with echo
"The guy who predicts the number of views from the title of Jaru Jaru's video"
Get the number of searches with a regular expression. SeleniumBasic VBA Python
I tried to get the authentication code of Qiita API with Python.
Get the number of visits to each page with ReportingAPI + Cloud Functions
Get the contents of git diff from python
Output the number of CPU cores in Python
[Python] Get / edit the scale label of the figure
[Python] Get the main topics of Yahoo News
Get the caller of a function in Python
Calculate the total number of combinations with python
Divide the string into the specified number of characters
Find the number of days in a month
[Python] Get the last updated date of the website
Minimize the number of polishings by combinatorial optimization
Get a list of Qiita likes by scraping
Get only the address part of NIC (eth0)
To get the path of the currently running python.exe
Determine the number of classes using the Starges formula
[Python] Get the day of the week (English & Japanese)
Get the update date of the Python memo file.
[Python] Automatically totals the total number of articles posted by Qiita using the API
Use twitter API to get the number of tweets related to a certain keyword
An introduction to data analysis using Python-To increase the number of video views-
Get the title of yahoo news and analyze sentiment
python beginners tried to predict the number of criminals
How to know the port number of the xinetd service
[Python] A program that counts the number of valleys
Get the variable name of the variable as a character string.
Transition of Qiita posts
Get the GNOME version
[Python] Get the official file path of the shortcut file (.lnk)
relation of the Fibonacci number series and the Golden ratio
The meaning of self
[Python] Get the text of the law from the e-GOV Law API
Get the sum of each of multiple columns with awk