-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add fastapi + service_info endpoint #78
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
44bd3de
feat: add fastapi + service_info endpoint
jsstevenson 72ddb79
add env var
jsstevenson e95f2e4
add other env names
jsstevenson 7c0a401
fix api version
jsstevenson 90eb8a0
add api tests and configs
jsstevenson 9197e78
more stash
jsstevenson 92765e5
add logging etc
jsstevenson fc1bb51
Merge branch 'main' into add-fastapi
jsstevenson e9a6131
other cleanup
jsstevenson d75bf44
add check
jsstevenson 7b24f46
cleanup
jsstevenson 492cec9
other fixes
jsstevenson 6719ef7
duh
jsstevenson 6a2dcd4
some cleanup + add fastapi
jsstevenson beae971
simplify
jsstevenson 8647ebc
prefer full import
jsstevenson 01ad0d4
style fixes
jsstevenson f4c59c2
update in quotes
jsstevenson 68faa36
move config class to config module
jsstevenson fa190af
fix
jsstevenson 9d4a589
Merge branch 'main' into add-fastapi
jsstevenson 79829bf
ope
jsstevenson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,17 @@ | ||
| """Provide hooks to run after project is generated.""" | ||
|
|
||
| from pathlib import Path | ||
| import shutil | ||
|
|
||
|
|
||
| if not {{ cookiecutter.add_docs }}: | ||
| shutil.rmtree("docs") | ||
| Path(".readthedocs.yaml").unlink() | ||
|
|
||
|
|
||
| if not {{ cookiecutter.add_fastapi }}: | ||
| Path("tests/test_api.py").unlink() | ||
| Path("src/{{ cookiecutter.project_slug }}/api.py").unlink() | ||
| Path("src/{{ cookiecutter.project_slug }}/models.py").unlink() | ||
| Path("src/{{ cookiecutter.project_slug }}/config.py").unlink() | ||
| Path("src/{{ cookiecutter.project_slug }}/logging.py").unlink() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
python/{{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| """{{ cookiecutter.description }}""" | ||
|
|
||
| from importlib.metadata import PackageNotFoundError, version | ||
|
|
||
|
|
||
|
|
||
65 changes: 65 additions & 0 deletions
65
python/{{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/api.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| """Define API endpoints.""" | ||
|
|
||
| from collections.abc import AsyncGenerator | ||
| from contextlib import asynccontextmanager | ||
| from enum import Enum | ||
|
|
||
| from fastapi import FastAPI | ||
|
|
||
| from {{ cookiecutter.project_slug }} import __version__ | ||
| from {{ cookiecutter.project_slug }}.config import config | ||
| from {{ cookiecutter.project_slug }}.logging import initialize_logs | ||
| from {{ cookiecutter.project_slug }}.models import ServiceInfo, ServiceOrganization, ServiceType | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def lifespan(app: FastAPI) -> AsyncGenerator: # noqa: ARG001 | ||
| """Perform operations that interact with the lifespan of the FastAPI instance. | ||
|
|
||
| See https://fastapi.tiangolo.com/advanced/events/#lifespan. | ||
|
|
||
| :param app: FastAPI instance | ||
| """ | ||
| initialize_logs() | ||
| yield | ||
|
|
||
|
|
||
| class _Tag(str, Enum): | ||
| """Define tag names for endpoints.""" | ||
|
|
||
| META = "Meta" | ||
|
|
||
|
|
||
| app = FastAPI( | ||
| title="{{ cookiecutter.project_slug }}", | ||
| description="{{ cookiecutter.description }}", | ||
| version=__version__, | ||
| contact={ | ||
| "name": "Alex H. Wagner", | ||
| "email": "[email protected]", | ||
| "url": "https://www.nationwidechildrens.org/specialties/institute-for-genomic-medicine/research-labs/wagner-lab", | ||
| }, | ||
| license={ | ||
| "name": "MIT", | ||
| "url": "https://github.com/{{ cookiecutter.org }}/{{ cookiecutter.repo }}/blob/main/LICENSE", | ||
| }, | ||
| docs_url="/docs", | ||
| openapi_url="/openapi.json", | ||
| swagger_ui_parameters={"tryItOutEnabled": True}, | ||
| ) | ||
|
|
||
|
|
||
| @app.get( | ||
| "/service_info", | ||
| summary="Get basic service information", | ||
| description="Retrieve service metadata, such as versioning and contact info. Structured in conformance with the [GA4GH service info API specification](https://www.ga4gh.org/product/service-info/)", | ||
| tags=[_Tag.META], | ||
| ) | ||
| def service_info() -> ServiceInfo: | ||
| """Provide service info per GA4GH Service Info spec | ||
|
|
||
| :return: conformant service info description | ||
| """ | ||
| return ServiceInfo( | ||
| organization=ServiceOrganization(), type=ServiceType(), environment=config.env | ||
| ) |
93 changes: 93 additions & 0 deletions
93
python/{{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/config.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """Read and provide runtime configuration.""" | ||
|
|
||
| import logging | ||
| import os | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| from {{ cookiecutter.project_slug }}.models import ServiceEnvironment | ||
|
|
||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| _ENV_VARNAME = "{{ cookiecutter.project_slug | upper }}_ENV" | ||
|
|
||
|
|
||
| class Config(BaseModel): | ||
| """Define app configuration data object.""" | ||
|
|
||
| env: ServiceEnvironment | ||
| debug: bool | ||
| test: bool | ||
|
|
||
|
|
||
| def _dev_config() -> Config: | ||
| """Provide development environment configs | ||
|
|
||
| :return: dev env configs | ||
| """ | ||
| return Config(env=ServiceEnvironment.DEV, debug=True, test=False) | ||
|
|
||
|
|
||
| def _test_config() -> Config: | ||
| """Provide test env configs | ||
|
|
||
| :return: test configs | ||
| """ | ||
| return Config(env=ServiceEnvironment.TEST, debug=False, test=True) | ||
|
|
||
|
|
||
| def _staging_config() -> Config: | ||
| """Provide staging env configs | ||
|
|
||
| :return: staging configs | ||
| """ | ||
| return Config(env=ServiceEnvironment.STAGING, debug=False, test=False) | ||
|
|
||
|
|
||
| def _prod_config() -> Config: | ||
| """Provide production configs | ||
|
|
||
| :return: prod configs | ||
| """ | ||
| return Config(env=ServiceEnvironment.PROD, debug=False, test=False) | ||
|
|
||
|
|
||
| def _default_config() -> Config: | ||
| """Provide default configs. This function sets what they are. | ||
|
|
||
| :return: default configs | ||
| """ | ||
| return _dev_config() | ||
|
|
||
|
|
||
| _CONFIG_MAP = { | ||
| ServiceEnvironment.DEV: _dev_config, | ||
| ServiceEnvironment.TEST: _test_config, | ||
| ServiceEnvironment.STAGING: _staging_config, | ||
| ServiceEnvironment.PROD: _prod_config, | ||
| } | ||
|
|
||
|
|
||
| def _set_config() -> Config: | ||
| """Set configs based on environment variable `{{ cookiecutter.project_slug | upper }}_ENV`. | ||
|
|
||
| :return: complete config object with environment-specific parameters | ||
| """ | ||
| raw_env_value = os.environ.get(_ENV_VARNAME) | ||
| if not raw_env_value: | ||
| return _default_config() | ||
| try: | ||
| env_value = ServiceEnvironment(raw_env_value.lower()) | ||
| except ValueError: | ||
| _logger.error( | ||
| "Unrecognized value for %s: '%s'. Using default configs", | ||
| _ENV_VARNAME, | ||
| raw_env_value | ||
| ) | ||
| return _default_config() | ||
| return _CONFIG_MAP[env_value]() | ||
|
|
||
|
|
||
| config = _set_config() |
16 changes: 16 additions & 0 deletions
16
python/{{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/logging.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| """Configure application logging.""" | ||
|
|
||
| import logging | ||
|
|
||
|
|
||
| def initialize_logs(log_level: int = logging.DEBUG) -> None: | ||
| """Configure logging. | ||
|
|
||
| :param log_level: app log level to set | ||
| """ | ||
| logging.basicConfig( | ||
| filename=f"{__package__}.log", | ||
| format="[%(asctime)s] - %(name)s - %(levelname)s : %(message)s", | ||
| ) | ||
| logger = logging.getLogger(__package__) | ||
| logger.setLevel(log_level) |
58 changes: 58 additions & 0 deletions
58
python/{{cookiecutter.project_slug}}/src/{{cookiecutter.project_slug}}/models.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| """Define models for internal data and API responses.""" | ||
|
|
||
| from enum import Enum | ||
| from typing import Literal | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| from . import __version__ | ||
|
|
||
|
|
||
| class ServiceEnvironment(str, Enum): | ||
| """Define current runtime environment.""" | ||
|
|
||
| DEV = "dev" | ||
| PROD = "prod" | ||
| TEST = "test" | ||
| STAGING = "staging" | ||
|
|
||
|
|
||
| class ServiceOrganization(BaseModel): | ||
| """Define service_info response for organization field""" | ||
|
|
||
| name: Literal["Genomic Medicine Lab at Nationwide Children's Hospital"] = ( | ||
| "Genomic Medicine Lab at Nationwide Children's Hospital" | ||
| ) | ||
| url: Literal[ | ||
| "https://www.nationwidechildrens.org/specialties/institute-for-genomic-medicine/research-labs/wagner-lab" | ||
| ] = "https://www.nationwidechildrens.org/specialties/institute-for-genomic-medicine/research-labs/wagner-lab" | ||
|
|
||
|
|
||
| class ServiceType(BaseModel): | ||
| """Define service_info response for type field""" | ||
|
|
||
| group: Literal["org.genomicmedlab"] = "org.genomicmedlab" | ||
| artifact: Literal["{{ cookiecutter.project_slug }} API"] = "{{ cookiecutter.project_slug }} API" | ||
| version: Literal[__version__] = __version__ | ||
|
|
||
|
|
||
| class ServiceInfo(BaseModel): | ||
| """Define response structure for GA4GH /service_info endpoint.""" | ||
|
|
||
| id: Literal["org.genomicmedlab.{{ cookiecutter.project_slug }}"] = ( | ||
| "org.genomicmedlab.{{ cookiecutter.project_slug }}" | ||
| ) | ||
| name: Literal["{{ cookiecutter.project_slug }}"] = "{{ cookiecutter.project_slug }}" | ||
| type: ServiceType | ||
| description: Literal["{{ cookiecutter.description }}"] = "{{ cookiecutter.description }}" | ||
| organization: ServiceOrganization | ||
| contactUrl: Literal["[email protected]"] = ( # noqa: N815 | ||
| "[email protected]" | ||
| ) | ||
| documentationUrl: Literal["https://github.com/{{ cookiecutter.org }}/{{ cookiecutter.repo }}"] = ( # noqa: N815 | ||
| "https://github.com/{{ cookiecutter.org }}/{{ cookiecutter.repo }}" | ||
| ) | ||
| createdAt: Literal["{% now 'utc', '%Y-%m-%dT%H:%M:%S+00:00' %}"] = "{% now 'utc', '%Y-%m-%dT%H:%M:%S+00:00' %}" # noqa: N815 | ||
| updatedAt: str | None = None # noqa: N815 | ||
| environment: ServiceEnvironment | ||
| version: Literal[__version__] = __version__ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| """Test FastAPI endpoint function.""" | ||
|
|
||
| from datetime import datetime | ||
| import re | ||
|
|
||
| import pytest | ||
| from fastapi.testclient import TestClient | ||
|
|
||
| from {{ cookiecutter.project_slug }}.api import app | ||
| from {{ cookiecutter.project_slug }}.models import ServiceEnvironment | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def api_client(): | ||
| return TestClient(app) | ||
|
|
||
|
|
||
| def test_service_info(api_client: TestClient): | ||
| response = api_client.get("/service_info") | ||
| assert response.status_code == 200 | ||
| expected_version_pattern = r"\d\.\d\." # at minimum, should be something like "0.1" | ||
| response_json = response.json() | ||
| assert response_json["id"] == "org.genomicmedlab.{{ cookiecutter.project_slug }}" | ||
| assert response_json["name"] == "{{ cookiecutter.project_slug }}" | ||
| assert response_json["type"]["group"] == "org.genomicmedlab" | ||
| assert response_json["type"]["artifact"] == "{{ cookiecutter.project_slug }} API" | ||
| assert re.match(expected_version_pattern, response_json["type"]["version"]) | ||
| assert response_json["description"] == "{{ cookiecutter.description }}" | ||
| assert response_json["organization"] == { | ||
| "name": "Genomic Medicine Lab at Nationwide Children's Hospital", | ||
| "url": "https://www.nationwidechildrens.org/specialties/institute-for-genomic-medicine/research-labs/wagner-lab", | ||
| } | ||
| assert response_json["contactUrl"] == "[email protected]" | ||
| assert ( | ||
| response_json["documentationUrl"] | ||
| == "https://github.com/{{ cookiecutter.org }}/{{ cookiecutter.repo }}" | ||
| ) | ||
| assert datetime.fromisoformat(response_json["createdAt"]) | ||
| assert ServiceEnvironment(response_json["environment"]) | ||
| assert re.match(expected_version_pattern, response_json["version"]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like there's still some merge conflicts that need resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good catch