Free tool

cURL to Dart converter

Paste a cURL command from your API docs or browser and get ready-to-use Flutter code for Dio or the http package. Add a sample response to get the model class too.

Dart code

import 'package:dio/dio.dart';

final dio = Dio();

Future<Order> createOrders() async {
  try {
    final response = await dio.post(
      'https://api.example.com/v1/orders',
      queryParameters: {
        'notify': 'true',
      },
      data: {
        'productId': 42,
        'quantity': 2,
        'note': 'Gift wrap',
      },
      options: Options(
        headers: {
          'Authorization': 'Bearer YOUR_TOKEN',
          'Content-Type': 'application/json',
        },
      ),
    );
    return Order.fromJson(response.data as Map<String, dynamic>);
  } on DioException catch (e) {
    // e.response is null when the server was never reached (no internet, timeout).
    final status = e.response?.statusCode;
    throw Exception('Request failed${status != null ? ' ($status)' : ''}: ${e.message}');
  }
}

class Order {
  const Order({
    required this.id,
    required this.status,
    required this.total,
    required this.items,
  });

  final int id;
  final String status;
  final double total;
  final List<Item> items;

  factory Order.fromJson(Map<String, dynamic> json) {
    return Order(
      id: json['id'] as int,
      status: json['status'] as String,
      total: (json['total'] as num).toDouble(),
      items: (json['items'] as List<dynamic>).map((e) => Item.fromJson(e as Map<String, dynamic>)).toList(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'status': status,
      'total': total,
      'items': items.map((e) => e.toJson()).toList(),
    };
  }
}

class Item {
  const Item({
    required this.productId,
    required this.quantity,
    required this.price,
  });

  final int productId;
  final int quantity;
  final double price;

  factory Item.fromJson(Map<String, dynamic> json) {
    return Item(
      productId: json['productId'] as int,
      quantity: json['quantity'] as int,
      price: (json['price'] as num).toDouble(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'productId': productId,
      'quantity': quantity,
      'price': price,
    };
  }
}

Add the package with flutter pub add dio

Nothing is sent anywhere: the command is converted in your browser, so tokens in your headers stay on your device.

Why I built this

Almost every API documents its endpoints as cURL commands: Stripe, Firebase REST, OpenAI, your own backend team’s Postman export. Turning one into Flutter code by hand means copying each header, moving the query string into a map, turning the JSON body into a Dart map, and then writing the model for the response. It is slow, and one missed header gives you a 401 that takes ages to track down.

Other converters I tried only output the http package. Most Flutter apps I work on use Dio for its interceptors, timeouts and form handling, so this one does both, and it reuses my JSON to Dart converter to build the response model in the same step.

How to use it

  • Copy a cURL command. In Chrome or Edge DevTools, open the Network tab, right-click a request and choose Copy → Copy as cURL (bash). In Postman, open the code panel (</>) and pick cURL.
  • Paste it into the left box and choose Dio or http.
  • Optional: paste a sample JSON response and set a class name. The function then returns that model (or a list of it) instead of raw data.
  • Copy the code, then add the package with flutter pub add dio or flutter pub add http.

What gets converted

  • Method: -X, or POST when there is a body and GET otherwise, just like cURL. -I becomes HEAD.
  • Headers: every -H, plus -A (User-Agent), -e (Referer) and -b (Cookie). Headers Dart sets for you, such as Content-Length and Accept-Encoding, are dropped.
  • Query string: moved into queryParameters, so values are encoded for you. Repeated keys (?tag=a&tag=b) become a list.
  • JSON body: -d, --data-raw or --json with JSON becomes a Dart map. Dio encodes it; with http it is wrapped in jsonEncode and a Content-Type header is added.
  • Form body: a=1&b=2 becomes a map sent as application/x-www-form-urlencoded.
  • File uploads: -F file=@photo.jpg becomes FormData with MultipartFile.fromFile in Dio, or http.MultipartRequest in http.
  • Basic auth: -u user:pass becomes an Authorization header built with base64Encode.
  • Timeouts: -m and --connect-timeout become Dart Durations.

I tested the output for a dozen kinds of command (JSON, forms, uploads, Basic auth, Chrome’s copied commands and more), for both clients, and it passes dart analyze with no issues.

Dio or http: which should you use?

http is the small, official package from the Dart team. It is enough for an app with a few simple GET and POST calls, and it is what most tutorials use. I explain it step by step in fetching API data in Flutter.

Dio is worth it once the app grows. It decodes JSON for you, has interceptors to add a token or refresh it in one place, supports timeouts, cancel tokens and upload progress, and throws a DioException for 4xx and 5xx responses so you don’t forget to check the status code.

Put the shared settings in one place

The converter writes one complete function per command. In a real app, move the base URL, timeouts and token into one shared Dio instance, then remove them from each function:

// lib/api/api_client.dart
final dio = Dio(BaseOptions(
  baseUrl: 'https://api.example.com/v1',
  connectTimeout: const Duration(seconds: 10),
  receiveTimeout: const Duration(seconds: 15),
  headers: {'Accept': 'application/json'},
));

// Add the token once instead of in every request.
void setToken(String token) {
  dio.options.headers['Authorization'] = 'Bearer $token';
}

And call the generated function from your UI, for example with a FutureBuilder:

FutureBuilder<Order>(
  future: createOrders(),
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.done) {
      return const CircularProgressIndicator();
    }
    if (snapshot.hasError) return Text('${snapshot.error}');
    return Text('Order #${snapshot.data!.id} is ${snapshot.data!.status}');
  },
)

Common problems when calling an API from Flutter

  • It works in cURL but returns 401 in the app: a header is missing, usually Authorization or an API key. Compare the generated headers with the original command, and don’t paste a token that has already expired.
  • XMLHttpRequest error on Flutter web: the API doesn’t allow requests from browsers (CORS). cURL and mobile apps aren’t affected. It has to be fixed on the server, or the call has to go through your own backend.
  • Cleartext HTTP traffic not permitted: Android blocks plain http:// URLs by default. Use https://, or allow cleartext only for local development.
  • Connection refused to localhost: on the Android emulator, localhost is the emulator itself. Use 10.0.2.2 to reach your computer.
  • type 'String' is not a subtype of type 'Map<String, dynamic>': the server didn’t send a JSON Content-Type, so Dio returned the body as text. Decode it yourself with jsonDecode(response.data as String), or ask the backend to send Content-Type: application/json.

FAQ

Is it safe to paste a command with my API key? The conversion runs in your browser and nothing is uploaded. Still, don’t ship secret keys inside a mobile app: anyone can extract them from the APK. Keep secrets on a server.

Does it support Windows cURL commands? Yes. Line endings with ^ (cmd) and ` (PowerShell) are handled, as are $'…' strings from Chrome’s “Copy as cURL (bash)”.

Can I get freezed or json_serializable models? Paste the same response into the JSON to Dart converter and pick the style there.

Want a full example? My Firebase login and sign-up guide and the Flutter projects with source code show API calls inside complete apps.

More free Flutter tools