interpret content-type header #296
12 changed files with 217 additions and 88 deletions
11
CHANGELOG.md
11
CHANGELOG.md
|
|
@ -1,3 +1,14 @@
|
|||
# 6.X.X (2026-XX-XX)
|
||||
|
||||
## New features
|
||||
|
||||
- Use the content-type header to determine the format of the request body
|
||||
in the `POST /<collection>/record/<class>`-endpoint and the
|
||||
`POST /<collection>/validate/record/<class>`-endpoint. For backward
|
||||
compatibility, the `format`-query parameter is still supported, it overrides
|
||||
the type information specified in the content-type header.
|
||||
|
||||
|
||||
# 6.7.1 (2026-11-05)
|
||||
|
||||
## Bugfixes
|
||||
|
|
|
|||
|
|
@ -344,7 +344,7 @@ def check_collection(
|
|||
if collection in g_recoverable_error:
|
||||
msg = (
|
||||
f"Collection '{collection}' has a recoverable configuration error. "
|
||||
"Please check the server logs for more information."
|
||||
'Please check the server logs for more information.'
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise HTTPException(
|
||||
|
|
@ -352,6 +352,7 @@ def check_collection(
|
|||
detail=msg,
|
||||
)
|
||||
|
||||
|
||||
def check_label(
|
||||
store_path: Path,
|
||||
abstract_config: Configuration,
|
||||
|
|
@ -577,8 +578,7 @@ def get_conflicting_paths(
|
|||
# If incoming and curated paths are not disjunct, the containing path
|
||||
# is added.
|
||||
containing_path, _ = _get_containing_path(
|
||||
collection_config.incoming,
|
||||
collection_config.curated
|
||||
collection_config.incoming, collection_config.curated
|
||||
)
|
||||
if containing_path:
|
||||
all_paths.add((containing_path, collection_name))
|
||||
|
|
@ -597,9 +597,27 @@ def get_conflicting_paths(
|
|||
containing_path, index = _get_containing_path(current_path, other_path)
|
||||
if containing_path:
|
||||
if index == 0:
|
||||
result.append((current_path, current_collection, usage_info[current_path], other_path, other_collection, usage_info[other_path]))
|
||||
result.append(
|
||||
(
|
||||
current_path,
|
||||
current_collection,
|
||||
usage_info[current_path],
|
||||
other_path,
|
||||
other_collection,
|
||||
usage_info[other_path],
|
||||
)
|
||||
)
|
||||
else:
|
||||
result.append((other_path, other_collection, usage_info[other_path], current_path, current_collection, usage_info[current_path]))
|
||||
result.append(
|
||||
(
|
||||
other_path,
|
||||
other_collection,
|
||||
usage_info[other_path],
|
||||
current_path,
|
||||
current_collection,
|
||||
usage_info[current_path],
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -403,7 +403,7 @@ def refresh_collection_state(
|
|||
print('refresh_collection_state called with argument:', a)
|
||||
if a % 100 >= 10:
|
||||
return None
|
||||
return (), dict(a=a+1)
|
||||
return (), dict(a=a + 1)
|
||||
|
||||
|
||||
def check_recoverable_errors(
|
||||
|
|
@ -420,7 +420,5 @@ def check_recoverable_errors(
|
|||
configuration=abstract_configuration,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
f'Error recovery failed: {e}'
|
||||
)
|
||||
logger.info(f'Error recovery failed: {e}')
|
||||
return (abstract_configuration, instance_state), {}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ from fastapi import (
|
|||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
Request,
|
||||
Response,
|
||||
)
|
||||
from fastapi_pagination import (
|
||||
|
|
@ -67,6 +68,7 @@ from dump_things_service.model import (
|
|||
from dump_things_service.utils import (
|
||||
authenticate_token,
|
||||
check_bounds,
|
||||
check_content_type,
|
||||
combine_ttl,
|
||||
get_token_store,
|
||||
join_default_token_permissions,
|
||||
|
|
@ -121,8 +123,7 @@ async def server() -> ServerResponse:
|
|||
ServerCollectionResponse(
|
||||
name=collection_name,
|
||||
schema=configuration.collections[collection_name].schema_location,
|
||||
classes=
|
||||
(
|
||||
classes=(
|
||||
instance_state.schema_info[
|
||||
configuration.collections[collection_name].schema_location
|
||||
].classes
|
||||
|
|
@ -237,22 +238,15 @@ async def store_record(
|
|||
body: dict | str,
|
||||
collection: str,
|
||||
class_name: str,
|
||||
request: Request,
|
||||
api_key: str = Depends(api_key_header_scheme),
|
||||
add_submission_tag: bool = False,
|
||||
format: Format = Format.json,
|
||||
format: Format | None = None,
|
||||
):
|
||||
format_, body = check_content_type(request, format, body)
|
||||
|
||||
configuration = get_config()
|
||||
|
||||
if format == Format.json and isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
|
||||
)
|
||||
|
||||
if format == Format.ttl and not isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
|
||||
)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
check_collection(configuration, collection)
|
||||
|
||||
|
|
@ -290,7 +284,7 @@ async def store_record(
|
|||
detail=f"No class named '{class_name}' found in collection '{collection}'.",
|
||||
)
|
||||
|
||||
if format == Format.ttl:
|
||||
if format_ == Format.ttl:
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
|
|
@ -318,7 +312,7 @@ async def store_record(
|
|||
submitter=user_id if add_submission_tag else None,
|
||||
)
|
||||
|
||||
if format == Format.ttl:
|
||||
if format_ == Format.ttl:
|
||||
format_converter = FormatConverter(
|
||||
configuration.collections[collection].schema_location,
|
||||
input_format=Format.json,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ from fastapi import (
|
|||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
Request,
|
||||
)
|
||||
from pydantic import (
|
||||
TypeAdapter,
|
||||
|
|
@ -12,7 +13,6 @@ from pydantic import (
|
|||
from starlette.responses import JSONResponse
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_400_BAD_REQUEST,
|
||||
HTTP_403_FORBIDDEN,
|
||||
HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
Format,
|
||||
|
|
@ -27,6 +27,7 @@ from dump_things_service.converter import FormatConverter
|
|||
from dump_things_service.instance_state import get_instance_state
|
||||
from dump_things_service.model import get_model_for_schema
|
||||
from dump_things_service.utils import (
|
||||
check_content_type,
|
||||
dict_to_base_model,
|
||||
get_token_store,
|
||||
join_default_token_permissions,
|
||||
|
|
@ -56,30 +57,15 @@ def validate_record(
|
|||
body: dict | str,
|
||||
collection: str,
|
||||
class_name: str,
|
||||
format: Format = Format.json,
|
||||
request: Request,
|
||||
format: Format | None = None,
|
||||
api_key: str | None = Depends(api_key_header_scheme),
|
||||
) -> JSONResponse:
|
||||
logger.info(
|
||||
'validate_record(%s, %s, %s, %s, *)',
|
||||
repr(body),
|
||||
collection,
|
||||
repr(class_name),
|
||||
repr(format),
|
||||
)
|
||||
format_, body = check_content_type(request, format, body)
|
||||
|
||||
instance_state = get_instance_state()
|
||||
abstract_config = get_config()
|
||||
|
||||
if format == Format.json and isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
|
||||
)
|
||||
|
||||
if format == Format.ttl and not isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
|
||||
)
|
||||
|
||||
check_collection(abstract_config, collection)
|
||||
|
||||
token = (
|
||||
|
|
@ -105,7 +91,7 @@ def validate_record(
|
|||
detail=f"Not authorized to validate records for collection '{collection}'.",
|
||||
)
|
||||
|
||||
if format == Format.ttl:
|
||||
if format_ == Format.ttl:
|
||||
with wrap_http_exception(
|
||||
ValueError,
|
||||
status_code=HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
|
|
|
|||
|
|
@ -178,20 +178,20 @@ disable_installed_extensions_check()
|
|||
|
||||
# Define the tag-order
|
||||
openapi_tags = [
|
||||
{"name": 'default'},
|
||||
{"name": 'Read records'},
|
||||
{"name": 'Store records'},
|
||||
{"name": 'Validate records'},
|
||||
{"name": 'Delete records'},
|
||||
{"name": 'Curated area: read records'},
|
||||
{"name": 'Curated area: store records'},
|
||||
{"name": 'Curated area: delete records'},
|
||||
{"name": 'Incoming area: read records'},
|
||||
{"name": 'Incoming area: read labels'},
|
||||
{"name": 'Incoming area: store records'},
|
||||
{"name": 'Incoming area: delete records'},
|
||||
{"name": 'Server management'},
|
||||
{"name": 'Administration interface'},
|
||||
{'name': 'default'},
|
||||
{'name': 'Read records'},
|
||||
{'name': 'Store records'},
|
||||
{'name': 'Validate records'},
|
||||
{'name': 'Delete records'},
|
||||
{'name': 'Curated area: read records'},
|
||||
{'name': 'Curated area: store records'},
|
||||
{'name': 'Curated area: delete records'},
|
||||
{'name': 'Incoming area: read records'},
|
||||
{'name': 'Incoming area: read labels'},
|
||||
{'name': 'Incoming area: store records'},
|
||||
{'name': 'Incoming area: delete records'},
|
||||
{'name': 'Server management'},
|
||||
{'name': 'Administration interface'},
|
||||
]
|
||||
|
||||
|
||||
|
|
@ -329,7 +329,7 @@ try:
|
|||
instance_state=g_instance_state,
|
||||
)
|
||||
except ConfigError as e:
|
||||
logger.error("There were errors manifesting configuration: %s", e)
|
||||
logger.error('There were errors manifesting configuration: %s', e)
|
||||
|
||||
|
||||
# Add a periodic task that tries to recover from recoverable errors in the
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ from typing import cast
|
|||
|
||||
from dump_things_service.abstract_config import (
|
||||
Configuration,
|
||||
TokenConfig, g_recoverable_error,
|
||||
TokenConfig,
|
||||
)
|
||||
from dump_things_service.collection import create_collection
|
||||
from dump_things_service.exceptions import (
|
||||
|
|
@ -103,7 +103,6 @@ def manifest_configuration(
|
|||
a collection.
|
||||
"""
|
||||
from dump_things_service.abstract_config import g_recoverable_error
|
||||
global g_recoverable_error
|
||||
|
||||
# Determine the changes in collections.
|
||||
existing_collections = set(instance_state.collections)
|
||||
|
|
@ -176,15 +175,14 @@ def manifest_configuration(
|
|||
# indicate that the configuration is not fully valid.
|
||||
if faulty_collections:
|
||||
for collection in faulty_collections:
|
||||
logger.info('removing fault-inducing configuration for collection "%s"', collection)
|
||||
logger.info(
|
||||
'removing fault-inducing configuration for collection "%s"', collection
|
||||
)
|
||||
configuration.collections.pop(collection, None)
|
||||
msg = (
|
||||
'Collection creation errors occurred:\n'
|
||||
+ '\n'.join(
|
||||
msg = 'Collection creation errors occurred:\n' + '\n'.join(
|
||||
f'creating collection "{collection_name}" failed due to: {error}'
|
||||
for collection_name, error in collection_errors.items()
|
||||
)
|
||||
)
|
||||
raise ConfigError(msg)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -7,8 +7,7 @@ from shutil import copyfile
|
|||
|
||||
import pytest
|
||||
import yaml
|
||||
from starlette.status import HTTP_400_BAD_REQUEST, \
|
||||
HTTP_422_UNPROCESSABLE_CONTENT
|
||||
from starlette.status import HTTP_400_BAD_REQUEST, HTTP_422_UNPROCESSABLE_CONTENT
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_200_OK,
|
||||
|
|
@ -26,12 +25,12 @@ from dump_things_service.abstract_config import (
|
|||
get_conflicting_paths,
|
||||
read_config,
|
||||
)
|
||||
from dump_things_service.abstract_config import g_recoverable_error
|
||||
from dump_things_service.collection import check_recoverable_errors
|
||||
from dump_things_service.endpoints.v0.collection_endpoints import CollectionRequest
|
||||
from dump_things_service.endpoints.v0.token_endpoints import TokenRequest
|
||||
from dump_things_service.exceptions import ConfigError
|
||||
from dump_things_service.instance_state import get_instance_state
|
||||
from dump_things_service.manifest import g_recoverable_error
|
||||
from dump_things_service.tests import schema_file
|
||||
|
||||
reference_config_file = Path(__file__).parent / 'assets' / 'reference_config.yaml'
|
||||
|
|
@ -340,7 +339,6 @@ def test_config_structure_error_detection(fastapi_client_simple):
|
|||
|
||||
|
||||
def test_is_directory_configuration_valid():
|
||||
|
||||
setup_info = (
|
||||
('c0.0', 'curated/c1', 'incoming/c1'),
|
||||
('c0.1', 'curated/c1/c2', 'incoming/c2'),
|
||||
|
|
@ -364,7 +362,7 @@ def test_is_directory_configuration_valid():
|
|||
'default_token': '',
|
||||
}
|
||||
for collection_name, curated, incoming in setup_info
|
||||
}
|
||||
},
|
||||
)
|
||||
conflicts = get_conflicting_paths(abstract_config)
|
||||
assert len(conflicts) == 17
|
||||
|
|
@ -386,6 +384,6 @@ def test_is_directory_configuration_valid():
|
|||
'default_token': '',
|
||||
}
|
||||
for collection_name, curated, incoming in setup_info
|
||||
}
|
||||
},
|
||||
)
|
||||
assert not get_conflicting_paths(abstract_config)
|
||||
|
|
|
|||
81
dump_things_service/tests/test_content_type.py
Normal file
81
dump_things_service/tests/test_content_type.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from dump_things_service import (
|
||||
HTTP_200_OK,
|
||||
HTTP_400_BAD_REQUEST,
|
||||
HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
)
|
||||
|
||||
json_record = {'given_name': 'Henry', 'pid': 'xyz:henry'}
|
||||
|
||||
ttl_record = """
|
||||
@prefix abc: <http://example.org/person-schema/abc/> .
|
||||
@prefix xyz: <https://www.example.com/xyz/> .
|
||||
xyz:henry a abc:Person ;
|
||||
abc:given_name "Henry" .
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.parametrize('path_part', ['record', 'validate/record'])
|
||||
def test_content_type_handling(fastapi_client_simple, path_part):
|
||||
test_client, _, _ = fastapi_client_simple
|
||||
|
||||
# Check that format-parameter overrides content-type-header
|
||||
response = test_client.post(
|
||||
f'/collection_1/{path_part}/Person?format=ttl',
|
||||
headers={
|
||||
'x-dumpthings-token': 'token-1',
|
||||
},
|
||||
json=json_record,
|
||||
)
|
||||
# Returns bad request because a JSON body is provided while the
|
||||
# format query-parameter specifies TTL
|
||||
assert response.status_code == HTTP_400_BAD_REQUEST
|
||||
|
||||
# Check that content-type is used when format-parameter is not provided
|
||||
response = test_client.post(
|
||||
f'/collection_1/{path_part}/Person',
|
||||
headers={
|
||||
'x-dumpthings-token': 'token-1',
|
||||
'content-type': 'text/turtle',
|
||||
},
|
||||
data=ttl_record,
|
||||
)
|
||||
assert response.status_code == HTTP_200_OK
|
||||
|
||||
# Check that content-type is used when format-parameter is not provided
|
||||
response = test_client.post(
|
||||
f'/collection_1/{path_part}/Person',
|
||||
headers={
|
||||
'x-dumpthings-token': 'token-1',
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
data=json.dumps(json_record),
|
||||
)
|
||||
assert response.status_code == HTTP_200_OK
|
||||
|
||||
# Check that faulty content is detected (JSON string provided while
|
||||
# content-type is text/turtle)
|
||||
response = test_client.post(
|
||||
f'/collection_1/{path_part}/Person',
|
||||
headers={
|
||||
'x-dumpthings-token': 'token-1',
|
||||
'content-type': 'text/turtle',
|
||||
},
|
||||
data=json.dumps(json_record),
|
||||
)
|
||||
assert response.status_code == HTTP_422_UNPROCESSABLE_CONTENT
|
||||
|
||||
# Check that format override works (format=json, which overrides
|
||||
# content-type is text/turtle)
|
||||
response = test_client.post(
|
||||
f'/collection_1/{path_part}/Person?format=json',
|
||||
headers={
|
||||
'x-dumpthings-token': 'token-1',
|
||||
'content-type': 'text/turtle',
|
||||
},
|
||||
data=json.dumps(json_record),
|
||||
)
|
||||
assert response.status_code == HTTP_200_OK
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
from dump_things_service import (
|
||||
HTTP_201_CREATED,
|
||||
HTTP_404_NOT_FOUND,
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ To speed up processing, multiple indices could be introduced, e.g.:
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
|
|
@ -20,20 +21,24 @@ from typing import (
|
|||
|
||||
import fsspec
|
||||
import yaml
|
||||
from fastapi import HTTPException
|
||||
from fastapi import (
|
||||
HTTPException,
|
||||
Request,
|
||||
)
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
TypeAdapter,
|
||||
ValidationError,
|
||||
)
|
||||
from rdflib import Graph
|
||||
from starlette.status import HTTP_422_UNPROCESSABLE_CONTENT
|
||||
|
||||
from dump_things_service import (
|
||||
Format,
|
||||
HTTP_400_BAD_REQUEST,
|
||||
HTTP_401_UNAUTHORIZED,
|
||||
HTTP_403_FORBIDDEN,
|
||||
HTTP_413_CONTENT_TOO_LARGE,
|
||||
HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
HTTP_503_SERVICE_UNAVAILABLE,
|
||||
)
|
||||
from dump_things_service.abstract_config import (
|
||||
|
|
@ -664,3 +669,44 @@ def dict_to_base_model(
|
|||
header='Validation error',
|
||||
):
|
||||
return TypeAdapter(getattr(model, class_name)).validate_python(data)
|
||||
|
||||
|
||||
def check_content_type(
|
||||
request: Request,
|
||||
format_override: Format | None,
|
||||
body: str | dict,
|
||||
) -> tuple[Format, str | dict]:
|
||||
"""Check that the content type is JSON or TTL
|
||||
|
||||
Content-type is determined by the content-type header of the request, unless
|
||||
the format_ parameter is provided. In that case the format_ parameter
|
||||
determines the format.
|
||||
"""
|
||||
if not format_override:
|
||||
content_type = request.headers.get('content-type', '').strip()
|
||||
if content_type not in ('application/json', 'text/turtle'):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid content type provided.',
|
||||
)
|
||||
specified_format = (
|
||||
Format.json if content_type == 'application/json' else Format.ttl
|
||||
)
|
||||
else:
|
||||
specified_format = format_override
|
||||
|
||||
if specified_format == Format.json:
|
||||
if isinstance(body, str):
|
||||
if format_override:
|
||||
# We don't care about the content-type and try to convert the
|
||||
# body into a JSON object.
|
||||
with wrap_http_exception(Exception):
|
||||
return Format.json, json.loads(body)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid JSON data provided.'
|
||||
)
|
||||
elif not isinstance(body, str):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST, detail='Invalid ttl data provided.'
|
||||
)
|
||||
return specified_format, body
|
||||
|
|
|
|||
Loading…
Reference in a new issue