Sample code for 30+ languages & platforms
Lianja

X.com Create Post

See more X Examples

Causes the User to create a Post under the authorized account.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

loHttp = createobject("CkHttp")

// Implements the following CURL command:

// curl -X POST "https://api.x.com/2/tweets" \
// -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
// -H "Content-Type: application/json" \
// -d '{"text":"Hello, X.com! This is my first post using the API."}'

// Use the following online tool to generate HTTP code from a CURL command
// Convert a cURL Command to HTTP Source Code

// Use this online tool to generate code from sample JSON:
// Generate Code to Create JSON

// The following JSON is sent in the request body.

// {
//   "text": "Hello, X.com! This is my first post using the API."
// }

loJson = createobject("CkJsonObject")
loJson.UpdateString("text","Hello, X.com! This is my first post using the API.")

// Adds the "Authorization: Bearer YOUR_ACCESS_TOKEN" header.
// Get our access token.
loJsonToken = createobject("CkJsonObject")
llSuccess = loJsonToken.LoadFile("qa_data/tokens/x.json")
if (llSuccess <> .T.) then
    ? "Failed to load x.json"
    release loHttp
    release loJson
    release loJsonToken
    return
endif

// Adds the "Authorization: Bearer <token>" header.
loHttp.AuthToken = loJsonToken.StringOf("access_token")

loResp = createobject("CkHttpResponse")
llSuccess = loHttp.HttpJson("POST","https://api.x.com/2/tweets",loJson,"application/json",loResp)
if (llSuccess = .F.) then
    ? loHttp.LastErrorText
    release loHttp
    release loJson
    release loJsonToken
    release loResp
    return
endif

loSbResponseBody = createobject("CkStringBuilder")
loResp.GetBodySb(loSbResponseBody)

loJResp = createobject("CkJsonObject")
loJResp.LoadSb(loSbResponseBody)
loJResp.EmitCompact = .F.

? "Response Body:"
? loJResp.Emit()

lnRespStatusCode = loResp.StatusCode
? "Response Status Code = " + str(lnRespStatusCode)
if (lnRespStatusCode >= 400) then
    ? "Response Header:"
    ? loResp.Header
    ? "Failed."
    release loHttp
    release loJson
    release loJsonToken
    release loResp
    release loSbResponseBody
    release loJResp
    return
endif

// Sample JSON response:
// (Sample code for parsing the JSON response is shown below)

// {
//   "data": {
//     "id": "1346889436626259968",
//     "text": "Hello, X.com! This is my first post using the API."
//   }
// }

// Sample code for parsing the JSON response...
// Use the following online tool to generate parsing code from sample JSON:
// Generate Parsing Code from JSON

lcId = loJResp.StringOf("data.id")
lcText = loJResp.StringOf("data.text")


release loHttp
release loJson
release loJsonToken
release loResp
release loSbResponseBody
release loJResp