Wordpress REST Api Authorization Help

james_sgp

Active Member
Licensed User
Longtime User
Hi, I am now working on using the WP REST API to confirm login details of my apps user. I`m using the following code, which is partially working; but I`m not getting the expected response from the API.

The code I`m using is
B4X:
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    
    Dim SU As StringUtils
    Dim s As String  =  "aaaa:bbbb"
    Dim e As String  = SU.EncodeBase64(s.GetBytes("UTF8"))
    
    Dim j As HttpJob
    j.Initialize("log-in", Me)
    j.PostString("https://www.ZZZZ.com/wp-json/wp/v2/posts", "")
    j.GetRequest.SetHeader("Authorization", "Basic " & e)
    Wait For (j) JobDone(job As HttpJob)
    If j.Success Then
        Log("SUCESS : " & j.GetString)
    Else
        j.Release
        Log("ERROR : " & j.ErrorMessage)
    End If
    
End Sub

But I`m getting the response :
B4X:
ERROR : {"code":"empty_content","message":"Content, title, and excerpt are empty.","data":{"status":400}}

I have tried changing the username & password and I get a message saying incorrect UN/PW (respectively), so would appear things are too far off.

But I am expecting something like this :
B4X:
[
    {
        "id": 1,
        "date": "2023-07-01T01:45:20",
        "date_gmt": "2023-07-01T01:45:20",
        "guid": {
            "rendered": "https://www.ZZZZ.com/?p=1"
        },
        "modified": "2023-07-01T01:45:20",
        "modified_gmt": "2023-07-01T01:45:20",
        "slug": "hello-world",
        "status": "publish",
        "type": "post",
        "link": "https://www.ZZZZ.com/2023/07/01/hello-world/",
        "title": {
            "rendered": "Hello world!"
        },
        "content": {
            "rendered": "\n<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n",
            "protected": false
        },
        "author": 1,
        "featured_media": 0,
        "comment_status": "open",
        "ping_status": "open",
        "sticky": false,
        "template": "",
        "format": "standard",
        "meta": [],
        "categories": [
            1
        ],
        "tags": [],
        "jetpack_featured_media_url": "",
        "_links": {
            "self": [
                {
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/posts/1"
                }
            ],
            "collection": [
                {
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/posts"
                }
            ],
            "about": [
                {
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/types/post"
                }
            ],
            "author": [
                {
                    "embeddable": true,
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/users/1"
                }
            ],
            "replies": [
                {
                    "embeddable": true,
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/comments?post=1"
                }
            ],
            "version-history": [
                {
                    "count": 0,
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/posts/1/revisions"
                }
            ],
            "wp:attachment": [
                {
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/media?parent=1"
                }
            ],
            "wp:term": [
                {
                    "taxonomy": "category",
                    "embeddable": true,
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/categories?post=1"
                },
                {
                    "taxonomy": "post_tag",
                    "embeddable": true,
                    "href": "https://www.ZZZZ.com/wp-json/wp/v2/tags?post=1"
                }
            ],
            "curies": [
                {
                    "name": "wp",
                    "href": "https://api.w.org/{rel}",
                    "templated": true
                }
            ]
        }
    }
]
 

mcqueccu

Well-Known Member
Licensed User
Longtime User
Please are you following the API Documentation?

Getting post list, single posts, post categories, comments etc does not need any username and password.

POST Endpoint:
https://example.com/wp-json/wp/v2/posts

The end point in your code is pointing to POSTS. If you are tryting to retrieve users, I think you should be using the USERS ENDPOINT

Base Users endpoint:
https://example.com/wp-json/wp/v2/users


Documentation
 

mcqueccu

Well-Known Member
Licensed User
Longtime User
To get all post as list, Try this code.Update the url and run


B4X:
sub loadAllPosts
    Dim url As String = $"https://YOUR DOMAIN.com/wp-json/wp/v2/posts"$
    
    Dim ok As HttpJob
    ok.Initialize("", Me)   
    ok.Download(url)
    
    Wait For Jobdone (ok As HttpJob)
    
    If ok.Success Then
        
        Dim res As String
        res = ok.GetString
        
        Log(res)
        
        Dim parser As JSONParser
        parser.Initialize(res)
        
        Dim RootPosts As List = parser.NextArray
        For Each colroot As Map In RootPosts
            Dim date As String = colroot.Get("date")
            Dim template As String = colroot.Get("template")
            Dim links As Map = colroot.Get("_links")
            Dim curies As List = links.Get("curies")
            For Each colcuries As Map In curies
                Dim templated As String = colcuries.Get("templated")
                Dim name As String = colcuries.Get("name")
                Dim href As String = colcuries.Get("href")
            Next
            Dim replies As List = links.Get("replies")
            For Each colreplies As Map In replies
                Dim href As String = colreplies.Get("href")
                Dim embeddable As String = colreplies.Get("embeddable")
            Next
            Dim version_history As List = links.Get("version-history")
            For Each colversion_history As Map In version_history
                Dim count As Int = colversion_history.Get("count")
                Dim href As String = colversion_history.Get("href")
            Next
'            Dim author As List = links.Get("author")
'            For Each colauthor As Map In author
'                Dim href As String = colauthor.Get("href")
'                Dim embeddable As String = colauthor.Get("embeddable")
'            Next
            Dim wp_term As List = links.Get("wp:term")
            For Each colwp_term As Map In wp_term
                Dim taxonomy As String = colwp_term.Get("taxonomy")
                Dim href As String = colwp_term.Get("href")
                Dim embeddable As String = colwp_term.Get("embeddable")
            Next
            Dim about As List = links.Get("about")
            For Each colabout As Map In about
                Dim href As String = colabout.Get("href")
            Next
            Dim self As List = links.Get("self")
            For Each colself As Map In self
                Dim href As String = colself.Get("href")
            Next
            Dim predecessor_version As List = links.Get("predecessor-version")
            For Each colpredecessor_version As Map In predecessor_version
                Dim id As Int = colpredecessor_version.Get("id")
                Dim href As String = colpredecessor_version.Get("href")
            Next
            Dim wp_featuredmedia As List = links.Get("wp:featuredmedia")
            For Each colwp_featuredmedia As Map In wp_featuredmedia
                Dim href As String = colwp_featuredmedia.Get("href")
                Dim embeddable As String = colwp_featuredmedia.Get("embeddable")
            Next
            Dim collection As List = links.Get("collection")
            For Each colcollection As Map In collection
                Dim href As String = colcollection.Get("href")
            Next
            Dim wp_attachment As List = links.Get("wp:attachment")
            For Each colwp_attachment As Map In wp_attachment
                Dim href As String = colwp_attachment.Get("href")
            Next
            Dim jetpack_featured_media_url As String = colroot.Get("jetpack_featured_media_url")
            Dim link As String = colroot.Get("link")
            Dim aType As String = colroot.Get("type")
            Dim title As Map = colroot.Get("title")
            Dim rendered As String = title.Get("rendered")
            Dim content As Map = colroot.Get("content")
            Dim rendered As String = content.Get("rendered")
            Dim protected As String = content.Get("protected")
            Dim featured_media As Int = colroot.Get("featured_media")
            Dim modified As String = colroot.Get("modified")
            Dim id As Int = colroot.Get("id")
            Dim categories As List = colroot.Get("categories")
            For Each colcategories As Int In categories
            Next
            Dim date_gmt As String = colroot.Get("date_gmt")
            Dim slug As String = colroot.Get("slug")
            Dim jetpack_publicize_connections As List = colroot.Get("jetpack_publicize_connections")
            Dim modified_gmt As String = colroot.Get("modified_gmt")
            Dim author As Int = colroot.Get("author")
            Dim format As String = colroot.Get("format")
            Dim comment_status As String = colroot.Get("comment_status")
            Dim tags As List = colroot.Get("tags")
            Dim ping_status As String = colroot.Get("ping_status")
'            Dim meta As Map = colroot.Get("meta")
'            Dim spay_email As String = meta.Get("spay_email")
'            Dim amp_status As String = meta.Get("amp_status")
'            Dim jetpack_publicize_message As String = meta.Get("jetpack_publicize_message")
'            Dim sticky As String = colroot.Get("sticky")
            Dim guid As Map = colroot.Get("guid")
            Dim rendered As String = guid.Get("rendered")
            Dim excerpt As Map = colroot.Get("excerpt")
'            Dim rendered As String = excerpt.Get("rendered")
'            Dim protected As String = excerpt.Get("protected")
            Dim status As String = colroot.Get("status")
            
            Dim ntitle As String = title.Get("rendered")
'           
'            Dim tem As HttpJob
'            tem.Initialize("",Me)
'            tem.Download(jetpack_featured_media_url)
'            Wait For Jobdone(tem As HttpJob)
            
'            If tem.Success Then
'                Dim bmp As B4XBitmap
'                bmp = tem.GetBitmapSample(500,500)
'            End If
            
'            Dim a As myDet
'            a.Initialize
'            a.tit = ntitle
'            a.urll = link
        '    lv.Add(CreateListItem(ntitle,date_gmt,bmp,lv.AsView.Width,120dip), link)
        
        Log(ntitle)
        Log(date_gmt)
    
        Log(link)
        Log("***********")
        
        Next
        
        Log("finished")
        ok.Release
    End If
    

End Sub
 

james_sgp

Active Member
Licensed User
Longtime User
Please are you following the API Documentation?

Getting post list, single posts, post categories, comments etc does not need any username and password.

POST Endpoint:
https://example.com/wp-json/wp/v2/posts

The end point in your code is pointing to POSTS. If you are tryting to retrieve users, I think you should be using the USERS ENDPOINT

Base Users endpoint:
https://example.com/wp-json/wp/v2/users


Documentation

I`m using the indicated code from the miniOrange API Plugin, which shows I should get the attached response. I tried changing the 'post' to user, but got a no route error in response:
B4X:
ERROR : {"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}


James
 

Attachments

  • Screenshot 2023-07-12 150708.jpg
    Screenshot 2023-07-12 150708.jpg
    53.4 KB · Views: 171

TILogistic

Expert
Licensed User
Longtime User
I`m using the indicated code from the miniOrange API Plugin, which shows I should get the attached response. I tried changing the 'post' to user, but got a no route error in response:
B4X:
ERROR : {"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}


James
test:
B4X:
Public Sub TESTWPGetURL
    Dim User As String  =  "aaaa"
    Dim Password As String =  "bbbb"
    Dim Auth As String = $"${User}:${Password}"$
    
    Dim Link As String = "https://www.ZZZZ.com/wp-json/wp/v2/posts"
    Dim SU As StringUtils
    Auth  = SU.EncodeBase64(Auth.GetBytes("UTF8"))
    
    Wait For (WPGetURL(Link, Auth)) Complete (DataResult As String)
    Log(DataResult)
End Sub


Public Sub WPGetURL(URL As String, Authorization As String) As ResumableSub
    Dim Result As String
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.Download(URL)
        j.GetRequest.SetHeader("Authorization", "Basic " & Authorization)
        j.GetRequest.SetHeader("Content-Type","application/json")
        j.GetRequest.Timeout = 60000
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Result = j.GetString
        Else
            Log(j.ErrorMessage)
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return Result
End Sub
 
  • Like
Reactions: byz

james_sgp

Active Member
Licensed User
Longtime User
test:
B4X:
Public Sub TESTWPGetURL
    Dim User As String  =  "aaaa"
    Dim Password As String =  "bbbb"
    Dim Auth As String = $"${User}:${Password}"$
   
    Dim Link As String = "https://www.ZZZZ.com/wp-json/wp/v2/posts"
    Dim SU As StringUtils
    Auth  = SU.EncodeBase64(Auth.GetBytes("UTF8"))
   
    Wait For (WPGetURL(Link, Auth)) Complete (DataResult As String)
    Log(DataResult)
End Sub


Public Sub WPGetURL(URL As String, Authorization As String) As ResumableSub
    Dim Result As String
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.Download(URL)
        j.GetRequest.SetHeader("Authorization", "Basic " & Authorization)
        j.GetRequest.SetHeader("Content-Type","application/json")
        j.GetRequest.Timeout = 60000
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Result = j.GetString
        Else
            Log(j.ErrorMessage)
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return Result
End Sub
Fantastic, that works...thanks...
Just for my understanding, your code seems to be waiting for responses more than mine did?
 

TILogistic

Expert
Licensed User
Longtime User
Just for my understanding, your code seems to be waiting for responses more than mine did?
1689158077316.png

If you call the process more than once, you will see the time decrease.
timeout can be 30 seconds by default, please remark it
 
Top