'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 1:[1]

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/

Solution 2:[2]

If you wanna using flutter as the frontend, I really recommend you to use dio and retrofit to handle the API integration. And those two packages would help you easily manage and handle all your API endpoints. Take the below image as an example enter image description here. You need to write the python as like:

@app.post("/merchant/change/password")
async def receive_keywords(
    confirmPassword: str = Query(None, alias='confirmPassword')
    merchantId: int = Query(None, alias='merchantId')
    newPassword: str = Query(None, alias='newPassword')
    oldPassword: str = Query(None, alias='oldPassword')
    session: str = Query(None, alias='session')
):
    return True

Solution 3:[3]

This is a JSON response without data, but you can add data you can change "Pong" for var. (This works to .post())

@_app.get("/")
def read_root():
    """Root route"""
    return {"Ping": "Pong"}

other example:

    response = {"limit": limit, "offset": offset, "data": users}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vismay Tiwari
Solution 2 Klaus Wong
Solution 3 idylicaro