Post Data to REST API

Create Free Backend With Appwrite

Introduction

Posting data to a REST API is a common requirement for mobile applications, enabling them to send information to a server for processing or storage. This guide demonstrates how to make POST requests in Flutter, using the http package.

Setup

Ensure the http package is included in your pubspec.yaml for making HTTP requests:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.1

Example: Creating a New Post

Here’s how you can post data to create a new post in a JSON placeholder API:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CreatePostExample(),
    );
  }
}

class CreatePostExample extends StatefulWidget {
  @override
  _CreatePostExampleState createState() => _CreatePostExampleState();
}

class _CreatePostExampleState extends State<CreatePostExample> {
  Future<void> createPost(String title, String body) async {
    final response = await http.post(
      Uri.parse('https://jsonplaceholder.typicode.com/posts'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        'title': title,
        'body': body,
        'userId': '1',
      }),
    );

    if (response.statusCode == 201) {
      // If the server returns a 201 CREATED response, then the post was successfully created.
      final responseBody = jsonDecode(response.body);
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Post Created"),
            content: Text("New post ID: ${responseBody['id']}"),
            actions: [
              MaterialButton(
                child: Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    } else {
      // If the server did not return a 201 CREATED response,
      // then throw an exception.
      throw Exception('Failed to create post');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Post Data Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => createPost('Flutter', 'Posting to API from Flutter'),
          child: const Text('Create Post'),
        ),
      ),
    );
  }
}
Run Online