When I tweet on Twitter API v2, I can't send a request at POST.

Asked 1 years ago, Updated 1 years ago, 142 views

Prerequisites/What you want to achieve

I would like to tweet using Twitter API v2 on Flutter.
The GET request, such as Timeline acquisition, has been successfully obtained as follows, but the POST request will return 403 as described in the Problem/Error Message.

The flow of source code processing is

Problems/Error Messages you are experiencing

flutter: {title:Forbiden, detail:Forbiden, type:about:blank, status:403}

Source Codes Affected

import'package:flutter/material.dart';
import'package:oauth1/oauth1.dart'asoauth1;
import 'package: url_launcher/url_launcher.dart';
import 'root.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'dart:convert';

void main() {
  runApp(MyApp());
}

/*
void setData(String collection, Map data) {
  FirebaseFirestore.instance.collection(collection).add(data);
}
*/

class MyApp extensions StatelessWidget {
  @override
  Widget build (BuildContext context) {
    US>return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwitch:Colors.blue,
      ),
      home —MyWidget(),
    );
  }
}

class MyWidget extensions StatefulWidget{
  @override
  _MyWidgetState createState()=>_MyWidgetState();
}

class_MyWidgetState extensions State<MyWidget>{
  final controller = TextEditingController();
  final platform = oauth1.Platform(
    'https://api.twitter.com/oauth/request_token',
    'https://api.twitter.com/oauth/authorize',
    'https://api.twitter.com/oauth/access_token',
    oauth1.SignatureMethods.hmacSha1,
  );
  final clientCredentials = oauth1.ClientCredentials(
    '',
    '',
  );
  late final auth = oauth1.Authorization (clientCredentials, platform);
  oauth1.Credentials? tokenCredentials;

  @override
  void initState() {
    super.initState();


    // Authenticate with PIN by setting CallbackURL to "oob"
    auth.requestTemporaryCredentials('oob').then(res){
      tokenCredentials =res.credentials;
      // Open the login URL in launch()
      launch(auth.getResourceOwnerAuthorizationURI(tokenCredentials!.token));
    });
  }

  @override
  Widget build (BuildContext context) {
    US>return MaterialApp(
      home —Scaffold(
        body: Center(
          child —Column(
            mainAxisAlignment—MainAxisAlignment.center,
            children: [
              // Enter the PIN displayed after login
              TextFormField(
                controller:controller,
              ),
              ElevatedButton(
                onPressed:() async {
                  // Obtain Access Token from PIN entered
                  final pin = controller.text;
                  final verifier=pin;
                  final res = wait auth.requestTokenCredentials(
                    tokenCredentials!,
                    verifier,
                  );
                  print('Access Token:${res.credentials.token}');
                  print('Access Token Secret:${res.credentials.tokenSecret}');
                  /*
                  FirebaseFirestore.instance.collection('test_collection1').add({
                    'access_token':res.credentials.token,
                    'access_token_secret':res.credentials.tokenSecret,
                  });
                   */

                  // You can request to the API using the Access Token you obtained.
                  final client=oauth1.Client(
                    platform.signatureMethod,
                    clientCredentials,
                    res.credentials,
                  );
                  /*
                  final apiResponse=wait client.get(
                    Uri.parse(
                        'https://api.twitter.com/1.1/statuses/home_timeline.json?count=1'),
                  );
                  print(apiResponse.body);

                   */

                  final getResponse = wait client.get(
                    Uri.https(
                      'api.twitter.com',
                      '/2/tweets',
                      {'text': 'Hello World!!',
                    ),
                  );

                  final getBody=jsonDecode(getResponse.body.toString());
                  print(getBody);

                  final postResponse=await client.post(
                    Uri.https(
                      'api.twitter.com',
                      '/2/tweets',
                      {'text': 'Hello World!!',
                    ),
                  );

                  final postBody=jsonDecode(postResponse.body.toString());
                  print(postBody);
                },
                child:Text('Authentication'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

I changed the source code from I received the following response (I don't think OAuth 2.0 will authenticate).

If you need any other information, please let me know.

Supplementary Information

  • Flutter official page (how to use Twitter API)

  • For instructions on specifying Uri.https parameters, refer to Get Timeline above.

  • The result of writing the code using the parameters specified by suzukis.

    Error: Too many positional arguments: 1 allowed, but 2 found.
    Try removing the extra positional arguments.
    final res=awit client.post(

  • Returned Messages

    flutter: {errors: [{parameters: {ids: []}, message: The ids query parameter can not be empty}, {parameters: {text: [Hello World!!]}, message: The query parameter [text] is not one of [ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]}], title: Invalid Request, detail: One or more parameters to your request was invalid., type: https://api.twitter.com/2/problems/invalid-request}
    flutter: { errors: [{ parameters: { text: [Hello World!!] }, message: The query parameter [ text ] is not one of [expansion, tweet.fields, media.fields, poll.fields, place.fields, user.fields] }, title: Invalid request to request you }ter.com/2/problems/invalid-request}

Flutter official page (how to use Twitter API)

For instructions on specifying the Uri.https parameters, refer to Get Timeline above.

The result of writing the code using the parameter specification method that suzukis taught me.

Error: Too many positional arguments: 1 allowed, but 2 found.
Try removing the extra positional arguments.
final res=awit client.post(

Returned Messages

flutter: {errors: [{parameters: {ids: []}, message: The ids query parameter can not be empty}, {parameters: {text: [Hello World!!]}, message: The query parameter [text] is not one of [ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]}], title: Invalid Request, detail: One or more parameters to your request was invalid., type: https://api.twitter.com/2/problems/invalid-request}
flutter: { errors: [{ parameters: { text: [Hello World!!] }, message: The query parameter [ text ] is not one of [expansion, tweet.fields, media.fields, poll.fields, place.fields, user.fields] }, title: Invalid request to request you }ter.com/2/problems/invalid-request}

ios twitter oauth flutter dart

2022-09-30 20:24

1 Answers

final res=wait client.post(
                    Uri.https(
                      'api.twitter.com',
                      '/2/tweets',
                      {'text':'Test',
                    ),
                  );

I have to specify a JSON string for the body of the POST request, but I am sending it as a query parameter.

final res=wait client.post(
                    Uri.https(
                      'api.twitter.com',
                      '/2/tweets',
                    ),
                    "{'text':'Test'}"
                  );

I've never touched it, so I don't know if it's right or not, but I think it'll look like this.

First of all, it's here that I suddenly noticed, but there's a possibility that it's stuck in front of me.

  • What kind of request should I send
  • What kind of request does my code actually send

Let's proceed while confirming


2022-09-30 20:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.