Skip to content

Build FastAPI app as an Android Service #3033

Closed as not planned
Closed as not planned
@fwwucn

Description

@fwwucn

Can I build Python FastAPI app as an Android Service?

e.g. I have a FastAPI app (see below app.py), which hosts a http server, and provides an endpoint which can be called by http request.
I want it to be run on Android device as a background Android Service, in which hosts a http server and provides an endpoint too. Thus another Android app on the same phone can call it by http request.

app.py

from fastapi import FastAPI
from fastapi.responses import Response

app = FastAPI()

@app.get('/health')
async def health() -> Response:
    '''Health check.'''
    return Response(status_code=200)

if __name__=='__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=5000)

I can successfully build it as an AAR with p4a command:

p4a aar --private . --dist-name service --package=com.example.service --name "My Service" --version 1.0 --bootstrap=service_library --requirements=python3 --release --service=app:app.py --arch=arm64-v8a --arch=armeabi-v7a --ignore-setup-py --sdk-dir /home/user/.android/android-sdk --ndk-dir /home/user/.android/android-ndk --android-api=27

The service-release-1.0.aar was generated, and ServiceApp.class can be found in service-release-1.0.aar\classes.jar\com\example\service\. How to load ServiceApp.class and run as a HTTP server on Android device?

Or can I build it as an Android Service (APK?), which can be directly installed on Android device?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions