All topics

FastAPI interview questions

12 questions with answers. 269 open jobs in India ask for FastAPI.

  1. What is the difference between Uvicorn and Gunicorn+Uvicorn?

    Gunicorn is an application server that interacts with your web-application using the WSGI protocol. This means that Gunicorn can serve applications written in synchronous web-frameworks such as Flask or Django (more so for versions released before 2021). Gunicorn takes care of running multiple instances of your web application, making sure they are healthy and restart them as needed, distributing incoming requests across those instances and communicate with the web server. In addition to that, Gunicorn is pretty darn fast about it. A lot of effort has gone into optimizing it. Gunicorn itself is not compatible with FastAPI because FastAPI uses the fresh ASGI standard.

    Uvicorn is an application server that supports the ASGI protocol. It also has an option to start and run several worker processes. Nevertheless, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's.

    Uvicorn has a Gunicorn-compatible worker class. This will allow you to run asgi app in Gunicorn! So, if you want to have a good process manager at that level (at the Python level), you can use Gunicorn as the process manager of your asgi app!

    If you have a cluster of machines with Kubernetes, Docker Swarm or another similar complex system to manage distributed containers on multiple machines, then you will probably want to handle replication at the cluster level instead of using a process manager (like Gunicorn with workers) in each container. One of those distributed container management systems like Kubernetes normally has some integrated way of handling replication of containers while still supporting load balancing for the incoming requests. All at the cluster level. In those cases, you would probably want to build a Docker image from scratch, installing your dependencies, and running a single Uvicorn process instead of running something like Gunicorn with Uvicorn workers.

    From Stack Overflow: asked by MADFROST, answered by zo0M (CC BY-SA 4.0)

  2. Is it possible to use FastAPI with Django?

    Short Answer

    Yes it's possible with WSGIMiddleware.

    For example, you can use all Django features (yes admin too) with mounting, with this example code.

    import os
    from importlib.util import find_spec
    from configurations.wsgi import get_wsgi_application
    from fastapi import FastAPI
    from fastapi.middleware.wsgi import WSGIMiddleware
    from fastapi.staticfiles import StaticFiles
    from api import router
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
    os.environ.setdefault("DJANGO_CONFIGURATIN", "Localdev")
    application = get_wsgi_application()
    app = FastAPI()
    app.mount("/admin", WSGIMiddleware(application))
    app.mount("/static",
        StaticFiles(
             directory=os.path.normpath(
                  os.path.join(find_spec("django.contrib.admin").origin, "..", "static")
             )
       ),
       name="static",
    )
    

    Also this one is from WSGIMiddleware documentation, it's a more straight-forward example (This one is for Flask but it demonstrates the same idea.).

    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))
    

    From Stack Overflow: asked by Leonardo Guerreiro, answered by Yagiz Degirmenci (CC BY-SA 4.0)

  3. What are the best practices for structuring a FastAPI project?

    Harsha already mentioned my project generator but I think it can be helpful for future readers to explain the ideas behind of it.

    If you are going to serve your frontend something like yarn or npm. You should not worry about the structure between them. With something like axios or the Javascript's fetch you can easily talk with your backend from anywhere.

    When it comes to structuring the backend, if you want to render templates with Jinja, you can have something that is close to MVC Pattern.

    your_project
    ├── __init__.py
    ├── main.py
    ├── core
    │   ├── models
    │   │   ├── database.py
    │   │   └── __init__.py
    │   ├── schemas
    │   │   ├── __init__.py
    │   │   └── schema.py
    │   └── settings.py
    ├── tests
    │   ├── __init__.py
    │   └── v1
    │       ├── __init__.py
    │       └── test_v1.py
    └── v1
        ├── api.py
        ├── endpoints
        │   ├── endpoint.py
        │   └── __init__.py
        └── __init__.py 
    

    By using __init__ everywhere, we can access the variables from the all over the app, just like Django.

    Let's the folders into parts:

    • Core
      • models
        • database.py
      • schemas
        • users.py
        • something.py
      • settings.py
      • views (Add this if you are going to render templates)
        • v1_views.py
        • v2_views.py
    • tests
    • v1
    • v2

    Models

    It is for your database models, by doing this you can import the same database session or object from v1 and v2.

    Schemas

    Schemas are your Pydantic models, we call it schemas because it is actually used for creating OpenAPI schemas since FastAPI is based on OpenAPI specification we use schemas everywhere, from Swagger generation to endpoint's expected request body.

    settings.py

    It is for Pydantic's Settings Management which is extremely useful, you can use the same variables without redeclaring it, to see how it could be useful for you check out our documentation for Settings and Environment Variables

    Views

    This is optional if you are going to render your frontend with Jinja, you can have something close to MVC pattern

    • Core
      • views
        • v1_views.py
        • v2_views.py

    It would look something like this if you want to add views.

    Tests

    It is good to have your tests inside your backend folder.

    APIs

    Create them independently by APIRouter, instead of gathering all your APIs inside one file.

    Notes

    You can use absolute import for all your importing since we are using __init__ everywhere, see Python's packaging docs.

    So assume you are trying to import v1's endpoint.py from v2, you can simply do

    from my_project.v1.endpoints.endpoint import something
    

    From Stack Overflow: asked by Shivam Manswalia, answered by Yagiz Degirmenci (CC BY-SA 4.0)

  4. What are the advantages of using Depends in FastAPI over just calling a dependent function/class?

    FastAPI will also inject parameters from the request into your dependencies, and include them into the OpenApi specification.

    This allows you to re-use parameters, which can help you write less code, especially if your project grows large.

    Without the dependency injection you'd have to specify the parameters on every route, every time.

    In this example from the FastAPI docs we have common search parameters being shared.

    async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
        return {"q": q, "skip": skip, "limit": limit}
    @app.get("/items/")
    async def read_items(commons: dict = Depends(common_parameters)):
        return commons
    @app.get("/users/")
    async def read_users(commons: dict = Depends(common_parameters)):
        return commons
    

    From Stack Overflow: asked by Ojomio, answered by Gabriel Cappelli (CC BY-SA 4.0)

  5. Architecture Flask vs FastAPI

    This seemed a little interesting, so i ran a little tests with ApacheBench:

    Flask

    from flask import Flask
    from flask_restful import Resource, Api
    app = Flask(__name__)
    api = Api(app)
    class Root(Resource):
        def get(self):
            return {"message": "hello"}
    api.add_resource(Root, "/")
    

    FastAPI

    from fastapi import FastAPI
    app = FastAPI(debug=False)
    @app.get("/")
    async def root():
        return {"message": "hello"}
    

    I ran 2 tests for FastAPI, there was a huge difference:

    1. gunicorn -w 4 -k uvicorn.workers.UvicornWorker fast_api:app
    2. uvicorn fast_api:app --reload

    So here is the benchmarking results for 5000 requests with a concurrency of 500:

    FastAPI with Uvicorn Workers

    Concurrency Level:      500
    Time taken for tests:   0.577 seconds
    Complete requests:      5000
    Failed requests:        0
    Total transferred:      720000 bytes
    HTML transferred:       95000 bytes
    Requests per second:    8665.48 [#/sec] (mean)
    Time per request:       57.700 [ms] (mean)
    Time per request:       0.115 [ms] (mean, across all concurrent requests)
    Transfer rate:          1218.58 [Kbytes/sec] received
    Connection Times (ms)
                  min  mean[+/-sd] median   max
    Connect:        0    6   4.5      6      30
    Processing:     6   49  21.7     45     126
    Waiting:        1   42  19.0     39     124
    Total:         12   56  21.8     53     127
    Percentage of the requests served within a certain time (ms)
      50%     53
      66%     64
      75%     69
      80%     73
      90%     81
      95%     98
      98%    112
      99%    116
     100%    127 (longest request)
    

    FastAPI - Pure Uvicorn

    Concurrency Level:      500
    Time taken for tests:   1.562 seconds
    Complete requests:      5000
    Failed requests:        0
    Total transferred:      720000 bytes
    HTML transferred:       95000 bytes
    Requests per second:    3200.62 [#/sec] (mean)
    Time per request:       156.220 [ms] (mean)
    Time per request:       0.312 [ms] (mean, across all concurrent requests)
    Transfer rate:          450.09 [Kbytes/sec] received
    Connection Times (ms)
                  min  mean[+/-sd] median   max
    Connect:        0    8   4.8      7      24
    Processing:    26  144  13.1    143     195
    Waiting:        2  132  13.1    130     181
    Total:         26  152  12.6    150     203
    Percentage of the requests served within a certain time (ms)
      50%    150
      66%    155
      75%    158
      80%    160
      90%    166
      95%    171
      98%    195
      99%    199
     100%    203 (longest request)
    

    For Flask:

    Concurrency Level:      500
    Time taken for tests:   27.827 seconds
    Complete requests:      5000
    Failed requests:        0
    Total transferred:      830000 bytes
    HTML transferred:       105000 bytes
    Requests per second:    179.68 [#/sec] (mean)
    Time per request:       2782.653 [ms] (mean)
    Time per request:       5.565 [ms] (mean, across all concurrent requests)
    Transfer rate:          29.13 [Kbytes/sec] received
    Connection Times (ms)
                  min  mean[+/-sd] median   max
    Connect:        0   87 293.2      0    3047
    Processing:    14 1140 4131.5    136   26794
    Waiting:        1 1140 4131.5    135   26794
    Total:         14 1227 4359.9    136   27819
    Percentage of the requests served within a certain time (ms)
      50%    136
      66%    148
      75%    179
      80%    198
      90%    295
      95%   7839
      98%  14518
      99%  27765
     100%  27819 (longest request)
    

    Total results

    Flask: Time taken for tests: 27.827 seconds

    FastAPI - Uvicorn: Time taken for tests: 1.562 seconds

    FastAPI - Uvicorn Workers: Time taken for tests: 0.577 seconds

    With Uvicorn Workers FastAPI is nearly 48x faster than Flask, which is very understandable. ASGI vs WSGI, so i ran with 1 concurreny:

    FastAPI - UvicornWorkers: Time taken for tests: 1.615 seconds

    FastAPI - Pure Uvicorn: Time taken for tests: 2.681 seconds

    Flask: Time taken for tests: 5.541 seconds

    I ran more tests to test out Flask with a production server.

    5000 Request 1000 Concurrency

    Read the rest at the sourceFrom Stack Overflow: asked by Justin Yeoh, answered by Yagiz Degirmenci (CC BY-SA 4.0)

  6. Is there a way to kill uvicorn cleanly?

    That's because you're running uvicorn as your only server. uvicorn is not a process manager and, as so, it does not manage its workers life cycle. That's why they recommend running uvicorn using gunicorn+UvicornWorker for production.

    That said, you can kill the spawned workers and trigger it's shutdown using the script below:

    $ kill $(pgrep -P $uvicorn_pid)
    

    The reason why this works but not the kill on the parent pid is because when you ^C something, the signal is transmitted throughout all of its spawned processes that are attached to the stdin.

    From Stack Overflow: asked by Douglas, answered by Gustavo Kawamoto (CC BY-SA 4.0)

  7. is there a difference between running fastapi from uvicorn command in dockerfile and from pythonfile?

    Update (on 2022-12-31)

    As an update from @Marcelo Trylesinski, from uvicorn v 0.19.0, the --debug flag was removed (Ref #1640).

    No, there is no difference.

    The commadline run method (uvicorn app.main:app) and executing the app.py using python command (python app.py) are the same. Both methods are calling the uvicorn.main.run(...) function under the hood.

    In other words, the uvicorn command is a shortcut to the uvicorn.run(...) function.

    So, in your case the function call

    uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3)
    

    can be done by uvicorn commandline as,

    uvicorn app.app:app --host 0.0.0.0 --port 4557 --reload --debug --workers 3
    

    Side Notes

    The --debug option is hidden from the command line options help page, but it can be found in the source code. Thus, it feels running the app using uvicorn command can be considered as a production thing.

    From Stack Overflow: asked by cerofrais, answered by JPG (CC BY-SA 4.0)

  8. Is there a FastAPI way to access current Request data globally?

    A solution provided here defines a context manager, that you can access globally. For each request, you are extracting the relevant information (like headers) & pass it to the context manager.

    Since fastapi is built with Starlette, you can use the library starlette-context. It is creating a context object that you can use without passing it as argument. The main caveat is that you still need to pass a request object to all your routes.

    EDIT: In starlette-context==0.3.0 new middleware has been added. Starlette team started to discourage (here) the use of their BaseHTTPMiddleware, in particulary for StreamingResponse/FileResponse endpoints. You might want to use RawContextMiddleware which also doesn't require the request object but it's experimental as there is no documentation in Starlette for writing custom middleware without the interface. But it seems to be working.

    Sample code from this lib to illustrate:

    import uvicorn
    from fastapi import FastAPI
    from starlette.requests import Request
    from starlette.responses import JSONResponse
    from starlette.middleware import Middleware
    from starlette_context import context, plugins
    from starlette_context.middleware import RawContextMiddleware
    middleware = [
        Middleware(
            RawContextMiddleware,
            plugins=(
                plugins.RequestIdPlugin(),
                plugins.CorrelationIdPlugin()
            )
        )
    ]
    app = FastAPI(debug=True, middleware=middleware)
    @app.route('/')
    async def index(request: Request):  # This argument is still needed here
        return JSONResponse(context.data)  # Your context data
    uvicorn.run(app, host="0.0.0.0")
    

    From Stack Overflow: asked by Andrew Allaire, answered by Colin Le Nost (CC BY-SA 4.0)

  9. How do I return an image in FastAPI?

    If you already have the bytes of the image in memory

    Return a fastapi.responses.Response with your custom content and media_type.

    You'll also need to muck with the endpoint decorator to get FastAPI to put the correct media type in the OpenAPI specification.

    @app.get(
        "/image",
        # Set what the media type will be in the autogenerated OpenAPI specification.
        # fastapi.tiangolo.com/advanced/additional-responses/#additional-media-types-for-the-main-response
        responses = {
            200: {
                "content": {"image/png": {}}
            }
        },
        # Prevent FastAPI from adding "application/json" as an additional
        # response media type in the autogenerated OpenAPI specification.
        # https://github.com/tiangolo/fastapi/issues/3258
        response_class=Response
    )
    def get_image()
        image_bytes: bytes = generate_cat_picture()
        # media_type here sets the media type of the actual response sent to the client.
        return Response(content=image_bytes, media_type="image/png")
    

    See the Response documentation.

    If your image exists only on the filesystem

    Return a fastapi.responses.FileResponse.

    See the FileResponse documentation.

    Be careful with StreamingResponse

    Other answers suggest StreamingResponse. StreamingResponse is harder to use correctly, so I don't recommend it unless you're sure you can't use Response or FileResponse.

    In particular, code like this is pointless. It will not "stream" the image in any useful way.

    @app.get("/image")
    def get_image()
        image_bytes: bytes = generate_cat_picture()
        # ❌ Don't do this.
        image_stream = io.BytesIO(image_bytes)
        return StreamingResponse(content=image_stream, media_type="image/png")
    

    First of all, StreamingResponse(content=my_iterable) streams by iterating over the chunks provided by my_iterable. But when that iterable is a BytesIO, the chunks will be \n-terminated lines, which won't make sense for a binary image.

    And even if the chunk divisions made sense, chunking is pointless here because we had the whole image_bytes bytes object available from the start. We may as well have just passed the whole thing into a Response from the beginning. We don't gain anything by holding data back from FastAPI.

    Second, StreamingResponse corresponds to HTTP chunked transfer encoding. (This might depend on your ASGI server, but it's the case for Uvicorn, at least.) And this isn't a good use case for chunked transfer encoding.

    Chunked transfer encoding makes sense when you don't know the size of your output ahead of time, and you don't want to wait to collect it all to find out before you start sending it to the client. That can apply to stuff like serving the results of slow database queries, but it doesn't generally apply to serving images.

    Unnecessary chunked transfer encoding can be harmful. For example, it means clients can't show progress bars when they're downloading the file. See:

    From Stack Overflow: asked by Hooked, answered by Maxpm (CC BY-SA 4.0)

  10. FastAPI runs API calls in serial instead of parallel fashion

    As per FastAPI's docs:

    When you declare an endpoint with normal def instead of async def, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server).

    and:

    If you are using a third party library that communicates with something (a database, an API, the file system, etc.) and doesn't have support for using await, (this is currently the case for most database libraries), then declare your endpoints as normally, with just def.

    If your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use async def.

    You can mix def and async def in your endpoints as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.

    Thus, a def (synchronous) endpoint in FastAPI will still run in the event loop, but instead of calling it directly, which would block the server, FastAPI will run it in a separate thread from an external threadpool and then await it (more details on the external threadpool are given later on); hence, FastAPI will still work asynchronously. In other words, the server will process requests to such endpoints concurrently (at the cost, though, of spawning a new thread or reusing an existing one from the threadpool, for every incoming request to such endpoints). Whereas, async def endpoints run directly in the event loop—which runs in a single thread, typically the main thread of a process/worker, and here is created when calling uvicorn.run(), or the equivalent method of some other ASGI server—that is, the server will also process requests to such endpoints concurrently/asynchronously, as long as there is an await call to non-blocking operations inside such async def endpoints; usually, these are I/O-bound operations, such as waiting for (1) data from the client to be sent through the network, (2) contents of a file in the disk to be read, and (3) a database operation to finish.

    However, if an endpoint defined with async def does not await for some coroutine inside (i.e., a coroutine object is the result of calling an async def function), in order to give up time for other tasks in the event loop to run (e.g., requests to the same or other endpoints, background tasks, etc.), each request to such an endpoint will have to be completely finished (i.e., exit the endpoint), before returning control back to the event loop and allowing other tasks in the event loop to run (see this answer, if you would like to monitor all pending tasks in an event loop). In other words, in such cases, the server would be "blocked", and hence, any requests would be processed sequentially.

    Read the rest at the sourceFrom Stack Overflow: asked by Learning from masters, answered by Chris (CC BY-SA 4.0)

  11. How to read body as any valid json?

    You can find nearly everything inside the Request object

    You are able to get request body with request.json(), which will give you the parsed JSON as dictionary.

    from fastapi import Request, FastAPI
    @app.post("/dummypath")
    async def get_body(request: Request):
        return await request.json()
    

    If you want access the body as string, you can use request.body()

    From Stack Overflow: asked by caeus, answered by Yagiz Degirmenci (CC BY-SA 4.0)

  12. How can I enable CORS in FastAPI?

    you can find answer from this:fastapi cors

    then this is a very simple code to achieve it:

    1. create a python file and named it main.py.

    2. add code in this file.

    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    app = FastAPI()
    origins = ["*"]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    @app.get("/")
    async def main():
        return {"message": "Hello World"}
    

    and run this app:

    uvicorn main:app  --reload --host 0.0.0.0 --port 8000
    

    if you computer ip is 192.12.12.12

    you can check this link and just write a small javascript in html:

    <script>
            fetch("http://192.12.12.12:8000/").then((Response) => {
                return Response.json()
            }).then((data) => {
                console.log(data);
            })
        </script>
    

    From Stack Overflow: asked by user270199, answered by yuanzz (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.