brillenheini
brillenheini

Reputation: 963

Running FastAPI under IIS

currently I have a simple API running with Flask under a subdirectory of some internal IIS site. Now I thought it might be some idea to rewrite that API using FastAPI instead. Running the API on IIS isn't a hard thing, you have to create a web.config and so some stuff inside the IIS configuration. I know that this is using WSGI, but is there a possibility to use ASGI as well (maybe in combination with uvicorn and gunicorn)?

One thing which is important is that it must run under a certain subdirectory, call it <iis_internal_company_server>/myapi. In Flask I have included a well-known prefix middleware which works as expected. I was looking for something similar for FastAPI, is this may a case to use app.include_router(router, prefix='/myapi')?

Have done some research but did not find a solution. Maybe one of you may have some experience with it. If so, please share. Many thanks in advance.

Regards, Thomas

Upvotes: 3

Views: 10784

Answers (2)

INTz_
INTz_

Reputation: 71

In my case for deploy on IIS used wfastcgi.py

First of all please install a2wsgi

pip install a2wsgi

in main.py

from fastapi import FastAPI
from a2wsgi import ASGIMiddleware

app = FastAPI()

@app.get("/")
def read_main():
 return {"message": "Hello World"}

wsgi_app = ASGIMiddleware(app)

in web.config add this key in appSettings

<add key="WSGI_HANDLER" value="main.wsgi_app" />

Upvotes: 7

lsabi
lsabi

Reputation: 4456

My answer is too long for a single comment, but it's not a definitive answer.

  1. I did not understand completely the WSGI/ASGI stuff? You want to still run the Flask api together with Fastapi? Then Fastapi can do it. Check the docs https://fastapi.tiangolo.com/advanced/wsgi/. Hereby I report the example
from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
from flask import Flask, escape, request

flask_app = Flask(__name__)

@flask_app.route("/")
def flask_main():
    name = request.args.get("name", "World")
    return f"Hello, {escape(name)} from Flask!"

app = FastAPI()

@app.get("/v2")
def read_main():
    return {"message": "Hello World"}

app.mount("/v1", WSGIMiddleware(flask_app))
  1. What do you mean by subdirectory? You can put the code in whatever directory you want and then run it from there. Instead, if you want to have two apps running on the same IP address, as far as I know, your only chance is to run a gateway that will forward requests that start with /api to the Fastapi server, all other requests to the other server

EDIT based on the comment

  1. How can I fix FastAPI application error on Apache WSGI?. The server needs to be compatible with ASGI workers. I don't know which web server you're running, so I can't say anything.

  2. This point should already answer your question, doesn't it?

Upvotes: 0

Related Questions