Search code examples
flutterrestfastapipython-3.8

Interaction Between Flutter and FastAPI


Ubuntu 20.04LTS, with Python 3.8 for FastAPI, and Flutter 2.8.1, with Android SDK version 32.0.0.

I am trying to send a Map from Flutter to FastAPI. I have figured out how to POST, but how can I receive it from FastAPI side?

Is database necessary?

Flutter side:

import 'src/models/keywords_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get, post;
import 'dart:convert';

class SearchScreen extends StatefulWidget {
  const SearchScreen(List<KeywordsModel> keywords, {Key? key}) : super(key: key);


  @override
  _SearchScreenState createState() => _SearchScreenState();
}


class _SearchScreenState extends State<SearchScreen> {
  final _formKey = GlobalKey<FormState>();
  final List<String> keywords = [];
  final Map<String, dynamic> keywordsMap = {};

  
  Future<void> postKeywords(parsedJson) async {
    await post(Uri.http("10.0.2.2:8000", "/search"), body: parsedJson);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.search),
        onPressed: () {
          print('---------------' * 20);
          for (int i = 0 ; i < keywords.length ; i++) {
            keywordsMap["$i"] = keywords[i];
          }
          var parsedJson = json.encode(keywordsMap);
          postKeywords(parsedJson);
        },
      ),

/// Skipped many lines

    );
  }
}

FastAPI side:

from fastapi import FastAPI
import json


app = FastAPI()

@app.post("/search/")
async def receive_keywords():
    """What to Put Here?"""
    json.loads(?????)


Solution

  • You have to use Resonse or JsonResponse. you have to define a dict or map and then send it by wrapping in one of the above. Here is the link in case you want to read more. https://fastapi.tiangolo.com/advanced/response-directly/