unofficial_jisho_api_dart/lib/api.dart

61 lines
2.1 KiB
Dart
Raw Normal View History

2020-06-25 23:40:54 +02:00
/// This library provides search functions for searching/scraping Jisho.org.
2020-06-26 18:14:00 +02:00
///
2020-06-25 23:40:54 +02:00
/// It provides a built-in http client and performs async requests to the server
/// for different types of requests.
2020-06-25 22:42:16 +02:00
library unofficial_jisho_api;
2020-06-26 18:14:00 +02:00
2020-06-25 22:42:16 +02:00
import 'dart:convert';
2020-06-26 01:59:23 +02:00
import 'package:http/http.dart' as http;
2020-06-25 22:42:16 +02:00
import './src/exampleSearch.dart';
2020-06-26 01:59:23 +02:00
import './src/kanjiSearch.dart';
import './src/objects.dart';
2020-06-25 22:42:16 +02:00
import './src/phraseScrape.dart';
2020-06-26 01:59:23 +02:00
import './src/phraseSearch.dart';
2020-06-25 22:42:16 +02:00
/// Query the official Jisho API for a word or phrase
2020-06-26 18:14:00 +02:00
///
2020-06-25 22:42:16 +02:00
/// See https://jisho.org/forum/54fefc1f6e73340b1f160000-is-there-any-kind-of-search-api
/// for discussion about the official API.
Future<JishoAPIResult> searchForPhrase(String phrase) async {
final uri = uriForPhraseSearch(phrase);
2020-06-26 18:14:00 +02:00
return await http
.get(uri)
.then((response) => JishoAPIResult.fromJson(jsonDecode(response.body)));
2020-06-25 22:42:16 +02:00
}
/// Scrape Jisho.org for information about a kanji character.
Future<KanjiResult> searchForKanji(String kanji) async {
final uri = uriForKanjiSearch(kanji);
2020-06-26 18:14:00 +02:00
return http
.get(uri)
.then((response) => parseKanjiPageData(response.body, kanji));
2020-06-25 22:42:16 +02:00
}
/// Scrape Jisho.org for examples.
Future<ExampleResults> searchForExamples(String phrase) async {
final uri = uriForExampleSearch(phrase);
2020-06-26 18:14:00 +02:00
return http
.get(uri)
.then((response) => parseExamplePageData(response.body, phrase));
2020-06-25 22:42:16 +02:00
}
/// Scrape the word page for a word/phrase.
2020-06-26 18:14:00 +02:00
///
2020-06-25 22:42:16 +02:00
/// This allows you to get some information that isn't provided by the official API, such as
/// part-of-speech and JLPT level. However, the official API should be preferred
/// if it has the information you need. This function scrapes https://jisho.org/word/XXX.
/// In general, you'll want to include kanji in your search term, for example 掛かる
/// instead of かかる (no results).
Future<PhrasePageScrapeResult> scrapeForPhrase(String phrase) async {
final uri = uriForPhraseScrape(phrase);
2020-06-26 17:45:56 +02:00
final response = await http.get(uri);
if (response.statusCode == 404) {
return PhrasePageScrapeResult(
query: phrase,
found: false,
);
2020-06-25 22:42:16 +02:00
}
2020-06-26 17:45:56 +02:00
return parsePhrasePageData(response.body, phrase);
2020-06-26 18:14:00 +02:00
}