2
@route.post('/')
async def return_header(name: str = Header(...),
                       age: str = Header(...),country: str = Header(...),
                       json_body : dict = Body(...)):
  return get_data(json_headers, json_body)

What do I have to add in return_header function such that all the headers are stored in json_headers

def get_data(headers=None, body=None):
  url = ''
  certs = ''
  response = requests.post(url, cert=certs, headers=headers, json=body, 
  verify=False)
  return some_fun(response.json()) 
Chris
  • 18,724
  • 6
  • 46
  • 80
NanCode
  • 23
  • 3
  • You could use `headers=request.headers.raw`. I would also suggest using `httpx` instead of `requests`. See related answers [here](https://stackoverflow.com/a/73736138/17865804) and [here](https://stackoverflow.com/a/73770074/17865804). – Chris Oct 12 '22 at 12:52
  • My question is how to store all the header parameters in the post request in json_headers which is in the function return_header and pass the json_headers as params to get_data function. – NanCode Oct 12 '22 at 13:50

1 Answers1

0

here is a working script

import requests
from fastapi import FastAPI, Header, Body

app = FastAPI()


def get_data(headers=None, body=None):
    print(headers)
    print(body)
    url = ""
    certs = ""
    response = requests.post(url, cert=certs, headers=headers, json=body, verify=False)
    return some_fun(response.json())


@app.post("/")
async def return_header(
    name: str = Header(...),
    age: str = Header(...),
    country: str = Header(...),
    json_body: dict = Body(...),
):
    json_headers = {
        "name": name,
        "age": age,
        "country": country,
    }
    print(json_headers, "\n", json_body)
    return get_data(json_headers, json_body)

output:

{'name': 'test', 'age': 'test', 'country': 'test'}
{}
willwrighteng
  • 1,411
  • 11
  • 25
  • I would not suggest using a blocking operation such as `requests.post()` within an `async def` function. Please have a look at [this answer](https://stackoverflow.com/a/71517830/17865804) as to why, as well as [here](https://stackoverflow.com/a/73736138/17865804) and [here](https://stackoverflow.com/a/74239367/17865804) on how to use `httpx` instead – Chris Apr 23 '23 at 17:41