iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📖

Calling the Narou Novel API

に公開

Purpose

Shousetsuka ni Narou is a site where users can post and read novels. Perhaps That Time I Got Reincarnated as a Slime is the most famous example?

I happened to come across the Narou Novel API, so I decided to try calling it, even though I don't usually work with Web APIs.

Implementation

Import the necessary modules:

import io
import json
import gzip
import requests

Specifying the information I want

Narrow down the search items. This time, I want to target the "Novel Title," "Author Name," "Novel Synopsis," and "Genre." Also, to reduce the overall load, I will use the of field to filter only for the target information. This is explained under the "of parameter" in the API documentation.

# Desired information
attrs = ["title", "writer", "story", "genre"]

# Mapping from items to of parameters
attr2of = {
    "title": "t",
    "ncode": "n",
    "userid": "u",
    "writer": "w",
    "story": "s",
    "biggenre": "bg",
    "genre": "g",
    "keyword": "k",
    "general_firstup": "gf",
    "general_lastup": "gl",
    "noveltype": "nt",
    "end": "e",
    "general_all_no": "ga",
    "length": "l",
    "time": "ti",
    "isstop": "i",
    "isr15": "ir",
    "isbl": "ibl",
    "isgl": "igl",
    "iszankoku": "izk",
    "istensei": "its",
    "istenni": "iti",
    "pc_or_k": "p",
    "global_point": "gp",
    "daily_point": "dp",
    "weekly_point": "wp",
    "monthly_point": "mp",
    "quarter_point": "qp",
    "yearly_point": "yp",
    "fav_novel_cnt": "f",
    "impression_cnt": "imp",
    "review_cnt": "r",
    "all_point": "a",
    "all_hyoka_cnt": "ah",
    "sasie_cnt": "sa",
    "kaiwaritu": "ka",
    "novelupdated_at": "nu",
    "updated_at": "ua",
}

Wrapping the API

Since calling a raw Web API feels a bit cumbersome, I'll wrap it in Python functions. It's a bit of a lazy implementation, but here's how I did it.

There is a parameter called gzip, and

recommended to reduce transfer volume limits

was mentioned, so I decided to use it as well. If you don't use it, you can just change parts like json_data[0]["allcount"] to res.json()[0]["allcount"].

def get_allcount_for_keyword(url, keyword):
    payload = {
        "gzip": 5,
        "out": "json",
        "lim": 1,
        "order": "new",
        "keyword": 1,
        "word": keyword,
    }
    res = requests.get(url, params=payload)
    if res.status_code != 200:
        return None
    gzip_file = io.BytesIO(res.content)
    with gzip.open(gzip_file, "rt") as f:
        json_data = f.read()
    json_data = json.loads(json_data)
    return json_data[0]["allcount"]


def get_info(url, keyword, allcount, lim_per_page, page_no):
    # Display information for page `page_no`, assuming `lim_per_page` items per page
    st = (page_no - 1) * lim_per_page + 1

    # Should `lim_per_page` be overwritten if it's very close to `allcount`? 
    # I'll skip that implementation this time.

    payload = {
        "gzip": 5,
        "out": "json",
        "of": "-".join([attr2of[attr] for attr in attrs]),
        "lim": lim_per_page,
        "st": st,
        "order": "new",
        "keyword": 1,
        "word": keyword,
    }
    res = requests.get(url, params=payload)
    if res.status_code != 200:
        return []
    gzip_file = io.BytesIO(res.content)
    with gzip.open(gzip_file, "rt") as f:
        json_data = f.read()
    json_data = json.loads(json_data)
    return json_data[1:]

Let's try searching

It seems that keywords like "Saint" (聖女) are probably popular, so let's try searching with that.

I'll omit the specific output, but if you call the function as follows, the novel summary is displayed.

url = "https://api.syosetu.com/novelapi/api/"

keyword = "聖女"

allcount = get_allcount_for_keyword(url, keyword)
lim_per_page = 20
page_no = 1

for i, info in enumerate(get_info(url, keyword, allcount, lim_per_page, page_no)):
    print(f"[{(page_no - 1) * lim_per_page + 1 + i}]")
    for attr in attrs:
        value = info[attr]
        print(f"{attr}: {value}")
    print("-"*10)

Summary

Even looking at the Narou Novel API Sample Program "Simple Novel List with Pagination (PHP)", I don't understand PHP, so I tried implementing it in Python based on the general feel, and it somehow worked.

To be honest, I don't quite understand everything because there are many site-specific details and terms, but I might be able to gather some information by scraping. Since some simple analysis has been done in Trying out the Narou Novel API, it might be worth trying various things.

Usage limits are applied per IP address.
The daily usage limit is 80,000 or a transfer limit of 400 MBytes.
Usage limits apply for 24 hours from the first access.

Since there was a note about API usage like this, it seems best to be careful, and making use of gzip seems like a good idea.

GitHubで編集を提案

Discussion