Flutter http post request to GitHub API

I am a new flutter developer working on my first project.
I have a GitHub repository which host a REST api. When i use http.get, everything works fine but when i try to write files using the post method to the api, It doesn’t work. I have some authentication issues even if i use access tokens. I tried using client ID and client secret but it couldn’t help. I need a step by step guide on how to go about it. I’m really confused at this point. I need your help. Thank you

  Future postData() async {
    final url = Uri.parse(
        'https://api.github.com/repos/mypt-studio/papsapi/contents/user/detail.json');
    final content="{"username":"testuser", "repname":"john Doe"}";

    final Map<String, String> body = {
      'message': 'first post',
      'content': content,
    };
    final response = await http.post(url,
        body: jsonEncode(body), headers: {'Authorization': 'Bearer $PAT'});
    print(response.statusCode);
  }

I tried using client ID and client secret but it couldn’t help
The post request will be sent by the users in the app.

  • Have you tried also sending the User-Agent header?

    – 

  • No please, I don’t know about that

    – 

You also need to include the User-Agent header in your requests. As per the GitHub REST API docs:

All API requests must include a valid User-Agent header. The User-Agent header identifies the user or application that is making the request.

By default, GitHub CLI sends a valid User-Agent header. However, GitHub recommends using your GitHub username, or the name of your application, for the User-Agent header value. This allows GitHub to contact you if there are problems.

The following is an example User-Agent for an app named Awesome-Octocat-App:

User-Agent: Awesome-Octocat-App

Requests with no User-Agent header will be rejected. If you provide an invalid User-Agent header, you will receive a 403 Forbidden response.

So you request call would look like this:

final response = await http.post(url,
  body: jsonEncode(body),
  headers: {
    'Authorization': 'Bearer $PAT',
    'User-Agent': 'your_app.com',
  },
);

Where your_app.com is your application ID or any string that you would like to identify your calls as some API client.

Leave a Comment