Post Data to REST API

Create Free Backend With Appwrite


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.


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

    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() {

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

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

class _CreatePostExampleState extends State<CreatePostExample> {
  Future<void> createPost(String title, String body) async {
    final response = await
      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);
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Post Created"),
            content: Text("New post ID: ${responseBody['id']}"),
            actions: [
                child: Text("OK"),
                onPressed: () {
    } else {
      // If the server did not return a 201 CREATED response,
      // then throw an exception.
      throw Exception('Failed to create post');

  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