Code Monkey home page Code Monkey logo

wordpress_client's Introduction

wordpress_client

Pub Version
Dart Flutter WordPress
Easily interact with the Wordpress REST API. Get support for most common endpoints & CRUD operations.

โœจ Features

  • ๐Ÿ”„ Request Synchronization.
  • ๐Ÿ“ฆ API discovery support.
  • โฒ๏ธ Measures request completion time.
  • ๐Ÿ“ Supports all CRUD operations.
  • ๐ŸŒ Supports all common endpoints.
  • ๐ŸŽจ Custom Requests & Authorization systems.
  • ๐Ÿ” 3 Popular authorization methods.
  • ๐ŸŽฃ Events for preprocessing response operations.

๐Ÿ“– How to Use

1. Setup

Add wordpress_client in your pubspec.yaml:

dependencies:
 wordpress_client: ^8.3.7

๐Ÿ’ก Ensure you get the latest version here.

Import the package where you need:

import 'package:wordpress_client/wordpress_client.dart';

2. Initialization

You can initialize WordpressClient in two methods:

  • Default (Simple Method)
  • Advanced (with Bootstrapper for additional configurations)

Simple Method:

final baseUrl = Uri.parse('https://example.com/wp-json/wp/v2');
final client = WordpressClient(baseUrl: baseUrl);

client.initialize();

๐Ÿ“˜ Learn more about the Advanced Method here.

3. Sending Requests

Example to retrieve 20 recent WordPress posts in ascending order:

final request = ListPostRequest(
  page: 1,
  perPage: 20,
  order = Order.asc,
);

final wpResponse = await client.posts.list(request);

// Dart 3 style
switch (wpResponse) {
    case WordpressSuccessResponse():
      final data = wpResponse.data; // List<Post>
      break;
    case WordpressFailureResponse():
      final error = wpResponse.error; // WordpressError
      break;
}

// or
// wordpress_client style
final result = postsResponse.map(
    onSuccess: (response) {
      print(response.message);
      return response.data;
    },
    onFailure: (response) {
      print(response.error.toString());
      return <Post>[];
    },
);

Refer to the documentation for more request examples.

๐Ÿ”’ Supported Authorization

1. AppPasswordAuth

By the WordPress Team, this method uses basic HTTP authentication where credentials are passed with every request. Details

2. BasicJwtAuth

Developed by Enrique Chavez, it involves JSON Web Token (JWT) authentication where a token is issued and then used in subsequent requests. Details

3. UsefulJwtAuth

By Useful Team, this is another implementation using JWT for authentication purposes. Details

For custom authorization, check the Authorization Wiki.

๐Ÿ“‹ Supported REST Methods

Endpoint Create Read Update Delete
Posts โœ… โœ… โœ… โœ…
Comments โœ… โœ… โœ… โœ…
Categories โœ… โœ… โœ… โœ…
Tags โœ… โœ… โœ… โœ…
Users โœ… โœ… โœ… โœ…
Me โœ… โœ… โœ… โœ…
Media โœ… โœ… โœ… โœ…
Pages โœ… โœ… โœ… โœ…
Application Passwords โœ… โœ… โœ… โœ…
Search - โœ… - -
Post Revisions โŒ โŒ โŒ โŒ
Taxonomies โŒ โŒ โŒ โŒ
Post Types โŒ โŒ โŒ โŒ
Post Statuses โŒ โŒ โŒ โŒ
Settings โŒ โŒ โŒ โŒ

๐Ÿ“ข Custom Response Types

Learn how to implement Custom Requests here.

๐Ÿ“ฃ Feedback

  • ๐Ÿ› For bugs or feature requests, use the issue tracker.
  • ๐Ÿ’ก Contributions are always appreciated. PRs are welcome!

๐Ÿ“œ License

Licensed under MIT.


Support Me:

Buy Me A Coffee

wordpress_client's People

Contributors

almis90 avatar arunprakashg avatar emiliodallatorre avatar mikhaelpurba avatar sebasrobert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

wordpress_client's Issues

Problem creating new users

I get an error returned like.

flutter: {"code": "rest_cannot_create_user", "message": "You do not have permissions to create new users.", "data":{"status":401}}

How can I fix this?

static void init(String username, String password) {
//init Wordpress API
client = WordpressClient.initialize(
"https://www.site.it/",
"wp-json/wp/v2",
bootstrapper: (bootstrapper) => bootstrapper
.withDebugMode(true)
.withDefaultAuthorization(BasicAuth(username, password))
.build(),
);
}

Future<WordpressResponse<User?>> signup(
String username, String email, String password) async {
return await client.users.create(
WordpressRequest(
requestData: CreateUserRequest(
username: username,
email: email,
password: password,
),
),
);
}

to the init method I pass username and password of a user with administrator role

why not one import?

I had to import

import 'package:wordpress_client/requests.dart';
import 'package:wordpress_client/responses.dart';
import 'package:wordpress_client/wordpress_client.dart';

why?

Loading image from Wordpress on webapp Canvaskit failing

Hi @ArunPrakashG ,

Thanks again for your great support, I have a big problem loading images from a WordPress website in a Flutter web app with Canvaskit renderer, in a release mode I get this error:

Access to fetch at 'https://b2bboostify.co.uk/wp-content/uploads/2023/10/two-young-happy-businesswomen-celebrating-project-success-office.jpg' from origin 'https://b2boostify.web.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

error_image_load

I understand it's a very common problem, do you know a solution for this issue?

Thanks in advance!

wpResponse.data is empty

Hi-
Trying to implement this on an app I'm building but even with a WordpressSuccessResponse() the data varaible is empty in wpResponse.data

`
void fetchArticles() async {
final baseUrl = Uri.parse('https://mydomain.com/wp-json/wp/v2');
final client = WordpressClient(
baseUrl: baseUrl,
bootstrapper: (bootstrapper) => bootstrapper
.withStatisticDelegate((baseUrl, requestCount) {
//print('$baseUrl -> $requestCount');
})
.withDebugMode(true)
.build(),
);
client.initialize();

final request = ListPostRequest(
  page: 1,
  perPage: 1,
  order: Order.asc,
);

final wpResponse = await client.posts.list(request);
switch (wpResponse) {
  case WordpressSuccessResponse():
    final data = wpResponse.data; // List<Post>
    break;
  case WordpressFailureResponse():
    final error = wpResponse.error; // WordpressError
    break;
}

setState(() {});

}
`

With debug enabled, I can see the successful connection and even the WP data in the Response Text field of the response, but the wpResponse.data field remains empty.

Logs:
scratch_1.txt

Is this a bug or am I just implementing it incorrectly? Thanks for your help!

There is no such thing as PostCreateBuilder

Hi.

First of all, I personally thank you that created such a nice Wordpress library to implement APIs to Dart Native. I would like to ask you something. In your custom interface codes, you define PostCreateBuilder() class to request but inside the project, I can't import that class. It gives error which says PostCreateBuilder is not defined and does not suggest to add any library you wrote.

Can you fix that issue please?

Cant get it to work :(

Im stuck here. Im unsure why :( Could you please extend your example folder with an working flutter example app that can just be started. I think this should help to start.

Image Url extraction error

Hi first for your great package,

I have a problem extracting feature media URL, I tried in different ways:
posts[0].featuredImageUrl and response.data[0]["wp:featuredmedia"] but I get this error:

*** Request ***
uri: https://b2bboostify.co.uk/wp-json/wp/v2/posts?page=1&per_page=1&order=desc
method: GET
responseType: ResponseType.json
followRedirects: true
persistentConnection: true
connectTimeout: 0:01:00.000000
sendTimeout: 0:00:30.000000
receiveTimeout: 0:00:30.000000
receiveDataWhenStatusError: true
extra: {}
headers:
data:
null

<p>Morbi sagittis, sem quis lacinia faucibus, orci ipsum gravida tortor, vel interdum mi sapien ut justo. Nulla varius consequat magna, id molestie ipsum volutpat quis. Suspendisse consectetur fringilla luctus. Fusce id mi diam, non ornare orci. Pellentesque ipsum erat, facilisis ut venenatis eu, sodales vel dolor.</p>
<ul>
<li><strong>This is a unorder list</strong>. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis, sem quis lacinia faucibus, orci ipsum gravida tortor, vel interdum mi sapien ut justo.</li>
<li>Nulla varius consequat magna, id molestie ipsum volutpat quis. Suspendisse consectetur fringilla luctus.</li>
<li>Fusce id mi diam, non ornare orci. Pellentesque ipsum erat, facilisis ut venenatis eu, sodales vel dolor.</li>
</ul>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis, sem quis lacinia faucibus, orci ipsum gravida tortor, vel interdum mi sapien ut justo. Nulla varius consequat magna, id molestie ipsum volutpat quis. Suspendisse consectetur fringilla luctus. Fusce id mi diam, non ornare orci. Pellentesque ipsum erat, facilisis ut venenatis eu, sodales vel dolor.</p>
, protected: false}, excerpt: {rendered: <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis, sem quis lacinia faucibus, orci ipsum gravida tortor, vel interdum mi sapien ut justo. Nulla varius consequat magna, id molestie ipsum volutpat quis. Suspendisse consectetur fringilla suctus. Pellentesque ipsum erat, facilisis ut venenatis eu, sodales vel dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit&#8230;.</p>
, protected: false}, author: 1, featured_media: 8369, comment_status: open, ping_status: open, sticky: false, template: , format: standard, meta: {footnotes: }, categories: [2], tags: [], aioseo_notices: [], _links: {self: [{href: https://b2bboostify.co.uk/wp-json/wp/v2/posts/87}], collection: [{href: https://b2bboostify.co.uk/wp-json/wp/v2/posts}], about: [{href: https://b2bboostify.co.uk/wp-json/wp/v2/types/post}], author: [{embeddable: true, href: https://b2bboostify.co.uk/wp-json/wp/v2/users/1}], replies: [{embeddable: true, href: https://b2bboostify.co.uk/wp-json/wp/v2/comments?post=87}], version-history: [{count: 1, href: https://b2bboostify.co.uk/wp-json/wp/v2/posts/87/revisions}], predecessor-version: [{id: 8372, href: https://b2bboostify.co.uk/wp-json/wp/v2/posts/87/revisions/8372}], wp:featuredmedia: [{embeddable: true, href: https://b2bboostify.co.uk/wp-json/wp/v2/media/8369}], wp:attachment: [{href: https://b2bboostify.co.uk/wp-json/wp/v2/media?parent=87}], wp:term: [{taxonomy: category, embeddable: true, href: https://b2bboostify.co.uk/wp-json/wp/v2/categories?post=87}, {taxonomy: post_tag, embeddable: true, href: https://b2bboostify.co.uk/wp-json/wp/v2/tags?post=87}], curies: [{name: wp, href: https://api.w.org/{rel}, templated: true}]}}]

POSTS: 1
POST TITLE: {rendered: Satisfaction Lies in the Effort}
IMAGE POST: null
TITLE FORMATAT: Satisfaction Lies in the Effort

Please can you help me, thanks in advance!

Deciding what fields are included in posts result

Please help me to understand how can I control what the ListPostRequest() returns. The documentation (https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields) allows to limit the response, but it seems there's no way in the plugin to specify what fields are returned. In the current state the request retrieves full post content which is not always requied. For example I would prefer to get only a list of titles, excerpts and URLs from the API. Is there a way to do that?

Error when using tags.list()

final response = await client.tags.list(ListTagRequest(perPage: 20));

or

final response = await client.tags.list(ListTagRequest(search: 'apple'));

In both cases above, the following error occurs.

Unhandled exception:
type 'int' is not a subtype of type 'String' of 'value'
#0      _LinkedHashMapMixin.[]= (dart:collection-patch/compact_hash.dart)
#1      MapExtensions.addIfNotNull (package:wordpress_client/src/utilities/extensions/map_extensions.dart:14:9)
#2      ListTagRequest.build (package:wordpress_client/src/requests/list/list_tag.dart:43:9)
#3      ListOperation.list (package:wordpress_client/src/operations/list.dart:8:37)
...

so I edit following two lines in package:wordpress_client/src/requests/list/list_tag.dart, then it works.

43:      ..addIfNotNull('page', page.toString())
44:      ..addIfNotNull('per_page', perPage.toString())

please, check it.

first try crashed

Uncaught (in promise) Error: Instance of 'ClientNotReadyException'
at Object.throw_ [as throw] (errors.dart:288:49)
at wordpress_client_base.WordpressClient.new.getInterface (wordpress_client_base.dart:422:7)
at get posts [as posts] (wordpress_client_base.dart:160:31)
at blog_section.dart:69:39
at Generator.next ()
at runBody (async_patch.dart:84:54)
at Object._async [as async] (async_patch.dart:123:5)
at blog_section.dart:62:32
at ink_well._InkResponseState.new.handleTap (ink_well.dart:1154:21)
at tap.TapGestureRecognizer.new.invokeCallback (recognizer.dart:275:24)
at tap.TapGestureRecognizer.new.handleTapUp (tap.dart:654:11)
at [_checkUp] (tap.dart:311:5)
at tap.TapGestureRecognizer.new.handlePrimaryPointer (tap.dart:244:7)
at tap.TapGestureRecognizer.new.handleEvent (recognizer.dart:630:9)
at [_dispatch] (pointer_router.dart:98:12)
at pointer_router.dart:143:9
at LinkedMap.new.forEach (linked_hash_map.dart:21:13)
at [_dispatchEventToRoutes] (pointer_router.dart:141:17)
at pointer_router.PointerRouter.new.route (pointer_router.dart:127:7)
at binding$5.WidgetsFlutterBinding.new.handleEvent (binding.dart:465:19)
at binding$5.WidgetsFlutterBinding.new.dispatchEvent (binding.dart:445:14)
at binding$5.WidgetsFlutterBinding.new.dispatchEvent (binding.dart:331:11)
at [_handlePointerEventImmediately] (binding.dart:400:7)
at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (binding.dart:363:5)
at [_flushPointerEventQueue] (binding.dart:320:7)
at [_handlePointerDataPacket] (binding.dart:293:9)
at Object.invoke1 (platform_dispatcher.dart:1251:13)
at _engine.EnginePlatformDispatcher.new.invokeOnPointerDataPacket (platform_dispatcher.dart:269:5)
at [_onPointerData] (pointer_binding.dart:168:39)
at pointer_binding.dart:791:20
at pointer_binding.dart:720:14
at loggedHandler (pointer_binding.dart:317:16)
at Object._checkAndCall (operations.dart:367:37)
at Object.dcall (operations.dart:372:39)
at ret (js_allow_interop_patch.dart:17:11)

not returning response

I'm trying to get posts from wordpress and i'm not getting response back. i'm running latest version of the library. Am i missing something? Sorry still learning flutter.
Future<ResponseContainer<List<Post?>?>> getPosts() async { WordpressClient client; client = new WordpressClient('https://{obfiscatedurl}/wp-json', 'wp/v2'); ResponseContainer<List<Post?>?> posts = await client.posts .list((builder) => builder.withPerPage(20).withPageNumber(1).build()); print(posts.value!.first!.id); return posts; }

Login

How can I log into my app?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.