nasa 0.0.4 nasa: ^0.0.4 copied to clipboard
The easiest and powerful Dart/Flutter library for NASA APIs.
The easiest and powerful Dart/Flutter library for NASA APIs 🌎
- 1. Guide 🌎
1. Guide 🌎 #
This library provides the easiest way to use NASA APIs in Dart and Flutter apps.
Show some ❤️ and star the repo to support the project.
1.1. Features 💎 #
✅ The wrapper library for NASA APIs.
✅ Easily integrates with the Dart & Flutter apps.
✅ Provides response objects with a guaranteed safe types.
✅ Support all request parameters and response fields.
✅ Well documented and well tested.
✅ Supports the powerful automatic retry.
1.2. Getting Started ⚡ #
1.2.1. Install Library #
With Dart:
dart pub add nasa
Or With Flutter:
flutter pub add nasa
1.2.2. Import #
import 'package:nasa/nasa.dart';
1.2.3. Implementation #
import 'package:nasa/nasa.dart';
Future<void> main() async {
final nasa = NasaApi(
token: 'YOUR_TOKEN_HERE',
//! Automatic retry is available when server error or network error occurs
//! when communicating with the API.
retryConfig: RetryConfig(
maxAttempts: 5,
onExecute: (event) => print(
'Retry after ${event.intervalInSeconds} seconds...'
'[${event.retryCount} times]',
),
),
//! The default timeout is 10 seconds.
timeout: Duration(seconds: 20),
);
try {
final apod = await nasa.apod.lookupImage();
print(apod);
} on UnauthorizedException catch (e) {
print(e);
} on RateLimitExceededException catch (e) {
print(e);
} on DataNotFoundException catch (e) {
print(e);
} on NasaException catch (e) {
print(e);
}
}
1.3. Supported Endpoints 👀 #
1.3.1. APOD Service #
Endpoint | Method Name |
---|---|
[GET https://api.nasa.gov/planetary/apod](https://api.nasa.gov/#apod) | lookupImage |
1.4. Tips 🏄 #
1.4.1. Method Names #
nasa uses the following standard prefixes depending on endpoint characteristics. So it's very easy to find the method corresponding to the endpoint you want to use!
Prefix | Description |
---|---|
lookup | This prefix is attached to endpoints that reference specific images etc. |
search | This prefix is attached to endpoints that perform extensive searches. |
1.4.2. Null Parameter at Request #
In this library, parameters that are not required at request time, i.e., optional parameters, are defined as nullable. However, developers do not need to be aware of the null parameter when sending requests when using this library.
It means the parameters specified with a null value are safely removed and ignored before the request is sent.
For example, arguments specified with null are ignored in the following request.
1.4.3. JSON Serialization and Deserialization #
All NASA API responses obtained using nasa are returned stored in a safe type object. However, there may be cases where the raw JSON returned from the NASA API is needed when creating applications in combination with other libraries.
In that case, you can use the toJson
method provided by the NasaResponse
or other model objects to convert it to the raw JSON format returned by the NASA API.
The JSON converted by this toJson
method is completely equivalent to the JSON returned by the NASA API and can be deserialized by using the factory constructor fromJson
provided with each model object.
import 'package:nasa/nasa.dart';
Future<void> main() async {
final nasa = NasaApi(token: 'YOUR_TOKEN');
try {
final response = await nasa.apod.lookupImage();
//! You can get raw JSON from this response.
print(response.toJson());
//! Or you can get raw JSON from specific model object.
print(response.data.first.toJson());
} on NasaException catch (e) {
print(e);
}
}
You could also write like:
import 'package:nasa/nasa.dart';
Future<void> main() async {
final nasa = NasaApi(token: 'YOUR_TOKEN');
try {
final response = await nasa.apod.lookupImage();
//! Serialize & Deserialize
final json = response.data.toJson();
final apod = APODData.fromJson(json);
print(apod);
} on NasaException catch (e) {
print(e);
}
}
1.4.4. Change the Timeout Duration #
The library specifies a default timeout of 10 seconds for all API communications.
However, there may be times when you wish to specify an arbitrary timeout duration. If there is such a demand, an arbitrary timeout duration can be specified as follows.
import 'package:nasa/nasa.dart';
Future<void> main() {
final nasa = NasaApi(
token: 'YOUR_TOKEN_HERE',
//! The default timeout is 10 seconds.
timeout: Duration(seconds: 5),
);
}
1.4.5. Automatic Retry #
Due to the nature of this library's communication with external systems, timeouts may occur due to inevitable communication failures or temporary crashes of the server to which requests are sent.
When such timeouts occur, an effective countermeasure in many cases is to send the request again after a certain interval. And nasa provides an automatic retry feature as a solution to this problem.
The errors subject to retry are as follows.
- When the status code of the response returned from NASA is
500
or503
. - When the network is temporarily lost and
SocketException
is thrown. - When communication times out temporarily and
TimeoutException
is thrown
1.4.5.1. Exponential BackOff and Jitter
The easiest way to perform an automatic retry is to stop the process at a certain time and rerun it until it succeeds. However, if there is a network outage on NASA's servers, sending multiple requests to a specific server at the same time may further overload the server to which the request is sent and further reduce the success rate of retry attempts.
This problem can be solved by exponential number and adding a random number called Jitter, and this method is called the Exponential BackOff and Jitter algorithm. By adding a random number to the exponentially increasing retry interval, the retry interval can be distributed more flexibly.
It can be implemented as follows.
import 'package:nasa/nasa.dart';
Future<void> main() async {
final nasa = NasaApi(
token: 'YOUR_TOKEN_HERE',
//! Add these lines.
retryConfig: RetryConfig(
maxAttempts: 3,
),
);
}
In the above implementation, the interval increases exponentially for each retry count with jitter. It can be expressed by next formula.
(2 ^ retryCount) + jitter(Random Number between 0 ~ 3)
1.4.5.2. Do Something on Retry
It would be useful to output logging on retries and a popup notifying the user that a retry has been executed. So nasa provides callbacks that can perform arbitrary processing when retries are executed.
It can be implemented as follows.
import 'package:nasa/nasa.dart';
Future<void> main() async {
final nasa = NasaApi(
token: 'YOUR_TOKEN_HERE',
retryConfig: RetryConfig(
maxAttempts: 3,
//! Add this line.
onExecute: (event) => print('Retrying... ${event.retryCount} times.'),
),
);
}
The RetryEvent passed to the callback contains information on retries.
1.4.6. Thrown Exceptions #
nasa provides a convenient exception object for easy handling of exceptional responses and errors returned from NASA API.
Exception | Description |
---|---|
NasaException | The most basic exception object. For example |
UnauthorizedException | Thrown when authentication fails with the specified access token. |
RateLimitExceededException | Thrown when the request rate limit is exceeded. |
DataNotFoundException | Thrown when response has no body or data field in body string. |
Also, all of the above exceptions thrown from the nasa process extend NasaException. This means that you can take all exceptions as NasaException or handle them as certain exception types, depending on the situation.
However note that, if you receive an individual type exception, be sure to define the process so that the individual exception type is cached before NasaException. Otherwise, certain type exceptions will also be caught as NasaException.
Therefore, if you need to catch a specific type of exception in addition to NasaException, be sure to catch NasaException in the bottom catch clause as in the following example.
import 'package:nasa/nasa.dart';
Future<void> main() async {
final nasa = NasaApi(token: 'YOUR_TOKEN_HERE');
try {
final apod = await nasa.apod.lookupImage();
print(apod);
} on UnauthorizedException catch (e) {
print(e);
} on RateLimitExceededException catch (e) {
print(e);
} on DataNotFoundException catch (e) {
print(e);
} on NasaException catch (e) {
print(e);
}
}
1.5. Contribution 🏆 #
If you would like to contribute to nasa, please create an issue or create a Pull Request.
There are many ways to contribute to the OSS. For example, the following subjects can be considered:
- There are request parameters or response fields that are not implemented.
- Documentation is outdated or incomplete.
- Have a better way or idea to achieve the functionality.
- etc...
You can see more details from resources below:
Or you can create a discussion if you like.
Feel free to join this development, diverse opinions make software better!
1.6. Contributors #
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
1.7. Support ❤️ #
The simplest way to show us your support is by giving the project a star at GitHub and Pub.dev.
You can also support this project by becoming a sponsor on GitHub:
You can also show on your repository that your app is made with nasa by using one of the following badges:
[![Powered by nasa](https://img.shields.io/badge/Powered%20by-nasa-00acee.svg)](https://github.com/myConsciousness/nasa-api)
[![Powered by nasa](https://img.shields.io/badge/Powered%20by-nasa-00acee.svg?style=flat-square)](https://github.com/myConsciousness/nasa-api)
[![Powered by nasa](https://img.shields.io/badge/Powered%20by-nasa-00acee.svg?style=for-the-badge)](https://github.com/myConsciousness/nasa-api)
1.8. License 🔑 #
All resources of nasa is provided under the BSD-3
license.
Copyright 2023 Kato Shinya. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided the conditions.
Note
License notices in the source are strictly validated based on.github/header-checker-lint.yml
. Please check header-checker-lint.yml for the permitted standards.
1.9. More Information 🧐 #
nasa was designed and implemented by Kato Shinya (@myConsciousness).