-
Notifications
You must be signed in to change notification settings - Fork 14
Usage
You can use this library just like any other Dart package.
- Add
wordpress_client
as a dependency onpubspec.yaml
file on your project root. At the time of this writing, the latest package version is 5.1.0. Do check Package Page to get latest version.
dependencies:
wordpress_client: {latest}
- Import the library to your project class in which you want to use the library.
import 'package:wordpress_client/wordpress_client.dart';
-
Initializing the client can be done in two ways. It is recommended to initialize
WordpressClient
once and assign the instance to a variable for later use. Else, if you are using cookies, it may not work properly.- Simple method, Initialize with default values.
- Advanced method (with Bootstrapper to configure various settings like User Agent, Authorization etc)
WordpressClient client = new WordpressClient('https://www.replaceme.com/wp-json', 'wp/v2');
WordpressClient client = new WordpressClient(
'https://www.replaceme.com/wp-json',
'wp/v2',
bootstrapper: (bootstrapper) => bootstrapper
.withCookies(true) // To save cookies internally
.withDefaultUserAgent('wordpress_client/4.0.0')
.withDefaultMaxRedirects(5)
.withFollowRedirects(true)
.withDefaultAuthorizationBuilder(
(builder) => builder
.withUserName('test_user')
.withPassword('super_secret_password')
.withType(AuthorizationType.USEFUL_JWT)
.build(),
)
.withStatisticDelegate(
(baseUrl, endpoint, count) {
print('Request send to: $baseUrl ($count times)');
},
).build(),
);
- Now you are ready to send requests to Wordpress REST API. For example, to send request to get the latest 20 posts in your Wordpress site:
ResponseContainer<List<Post>> response = await client.posts.list(
(builder) => builder
.withPerPage(20)
.withPageNumber(1)
.sortResultsBy(FilterPostSortOrder.DATE)
.build(),
);
Here, the ResponseContainer<T>
holds result T
object, in this case, its List<Post>
as we requested for list of latest posts, with some statistical data, like the time taken for the request to complete (it doesn't count the time taken to process the response information, just the raw request) as a Duration()
object.
T value; // the actual response object
int responseCode; // the response code
Map<String, dynamic> responseHeaders; // the headers returned from the server
Duration duration; // time taken for the request to complete as [Duration]
String message; // any messages regarding the request (errors/info, etc)
More than this, there are 2 properties on ResponseContainer<T>
.
int totalPagesCount;
int totalPostsCount;
List
responses from Wordpress contains total pages and total posts in the headers. These values help with pagination. these properties are a simple getter which checks the received headers for these values and parses them as int for ease of using them. They are still included in responseHeaders
inside ResponseContainer<T>
for manual parsing if required!