简体   繁体   English

使用 FastAPI 发布到外部 url

[英]POST to external url with FastAPI

I've been trying to figure out how to properly do a POST with FastAPI.我一直在尝试弄清楚如何使用 FastAPI 正确执行 POST。

I'm currently doing a POST with python's "requests module" and passing some json data as shown below:我目前正在使用 python 的“请求模块”进行 POST 并传递一些 json 数据,如下所示:

import requests
from fastapi import FastAPI

json_data = {"user" : MrMinty, "pass" : "password"} #json data
endpoint = "https://www.testsite.com/api/account_name/?access_token=1234567890" #endpoint
print(requests.post(endpoint, json=json_data). content)

I don't understand how to do the same POST using just FastAPI's functions, and reading the response.我不明白如何仅使用 FastAPI 的函数并阅读响应来执行相同的 POST。

The module request is not a FastAPI function, but is everything you need, first you need to have your FastAPI server running, either in your computer or in a external server that you have access.模块请求不是 FastAPI function,而是您需要的一切,首先您需要让 FastAPI 服务器在您的计算机或您有权访问的外部服务器中运行。

Then you need to know the IP or domain of your server, and then you make the request:然后你需要知道你的服务器的 IP 或域,然后你发出请求:

import requests
some_info = {'info':'some_info'}
head = 'http://192.168.0.8:8000' #IP and port of your server 
# maybe in your case the ip is the localhost 
requests.post(f'{head}/send_some_info', data=json.dumps(tablea))
# "send_some_info" is the address of your function in fast api

Your FastApI script would look like this, and should be running while you make your request:您的 FastApI 脚本将如下所示,并且应该在您发出请求时运行:

from fastapi import FastAPI
app = FastAPI()

@app.post("/send_some_info")
async def test_function(dict: dict[str, str]):
    # do something
    return 'Success'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM