endpoints.py 7.02 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Copyright 2018 Markus Scheidgen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an"AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from flask_restplus import Resource, abort
from flask import request
17
from elasticsearch_dsl import Q
18
19

from nomad import search
20
from nomad.metainfo.optimade import OptimadeEntry
21
22
23
24
25
26
27

from .api import api, url
from .models import json_api_single_response_model, entry_listing_endpoint_parser, Meta, \
    Links, CalculationDataObject, single_entry_endpoint_parser, base_endpoint_parser
from .filterparser import parse_filter, FilterException


28
29
30
ns = api.namespace('', description='The (only) API namespace with all OPTiMaDe endpoints.')


31
32
33
34
35
36
37
38
39
40
# TODO replace with decorator that filters response_fields
def base_request_args():
    if request.args.get('response_format', 'json') != 'json':
        abort(400, 'Response format is not supported.')

    properties_str = request.args.get('response_fields', None)
    if properties_str is not None:
        return properties_str.split(',')
    return None

41
42
43
44
45
46

def base_search_request():
    """ Creates a search request for all public and optimade enabled data. """
    return search.SearchRequest().owner('all', None).query(
        Q('exists', field='optimade.nelements'))  # TODO use the elastic annotations when done

47

48
@ns.route('/calculations')
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class CalculationList(Resource):
    @api.doc('list_calculations')
    @api.response(400, 'Invalid requests, e.g. bad parameter.')
    @api.expect(entry_listing_endpoint_parser, validate=True)
    @api.marshal_with(json_api_single_response_model, skip_none=True, code=200)
    def get(self):
        """ Retrieve a list of calculations that match the given Optimade filter expression. """
        request_fields = base_request_args()

        try:
            filter = request.args.get('filter', None)
            page_limit = int(request.args.get('page_limit', 10))
            page_number = int(request.args.get('page_number', 1))
            sort = request.args.get('sort', 'chemical_formula_reduced'),

        except Exception:
            abort(400, message='bad parameter types')  # TODO Specific json API error handling

67
68
        search_request = base_search_request()

69
70
71
72
73
74
75
76
77
78
79
80
        if filter is not None:
            try:
                search_request.query(parse_filter(filter))
            except FilterException as e:
                abort(400, message='Could not parse filter expression: %s' % str(e))

        result = search_request.execute_paginated(
            page=page_number,
            per_page=page_limit)
        # order_by='optimade.%s' % sort)  # TODO map the Optimade property

        available = result['pagination']['total']
81
82
        results = search.to_calc_with_metadata(result['results'])
        assert len(results) == len(result['results']), 'Mongodb and elasticsearch are not consistent'
83
84
85
86

        return dict(
            meta=Meta(
                query=request.url,
87
                returned=len(results),
88
                available=available,
89
                last_id=results[-1].calc_id if available > 0 else None),
90
91
92
93
94
95
            links=Links(
                'calculations',
                available=available,
                page_number=page_number,
                page_limit=page_limit,
                sort=sort, filter=filter),
96
            data=[CalculationDataObject(d, request_fields=request_fields) for d in results]
97
98
99
        ), 200


100
@ns.route('/calculations/<string:id>')
101
102
103
104
105
106
107
108
109
class Calculation(Resource):
    @api.doc('retrieve_calculation')
    @api.response(400, 'Invalid requests, e.g. bad parameter.')
    @api.response(404, 'Id does not exist.')
    @api.expect(single_entry_endpoint_parser, validate=True)
    @api.marshal_with(json_api_single_response_model, skip_none=True, code=200)
    def get(self, id: str):
        """ Retrieve a single calculation for the given id. """
        request_fields = base_request_args()
110
        search_request = base_search_request().search_parameters(calc_id=id)
111
112
113
114
115
116

        result = search_request.execute_paginated(
            page=1,
            per_page=1)

        available = result['pagination']['total']
117
118
119
        results = search.to_calc_with_metadata(result['results'])
        assert len(results) == len(result['results']), 'Mongodb and elasticsearch are not consistent'

120
121
122
123
124
        if available == 0:
            abort(404, 'The calculation with id %s does not exist' % id)

        return dict(
            meta=Meta(query=request.url, returned=1),
125
            data=CalculationDataObject(results[0], request_fields=request_fields)
126
127
128
        ), 200


129
@ns.route('/info/calculation')
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
class CalculationInfo(Resource):
    @api.doc('calculations_info')
    @api.response(400, 'Invalid requests, e.g. bad parameter.')
    @api.expect(base_endpoint_parser, validate=True)
    @api.marshal_with(json_api_single_response_model, skip_none=True, code=200)
    def get(self):
        """ Returns information relating to the API implementation- """
        base_request_args()

        result = {
            'type': 'info',
            'id': 'calculation',
            'attributes': {
                'description': 'A calculations entry.',
                # TODO non optimade, nomad specific properties
                'properties': {
                    attr.name: dict(description=attr.description)
147
                    for attr in OptimadeEntry.m_def.all_properties.values()
148
149
150
                },
                'formats': ['json'],
                'output_fields_by_format': {
151
                    'json': OptimadeEntry.m_def.all_properties.keys()
152
153
154
155
156
157
158
159
160
161
                }
            }
        }

        return dict(
            meta=Meta(query=request.url, returned=1),
            data=result
        ), 200


162
@ns.route('/info')
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
class Info(Resource):
    @api.doc('info')
    @api.response(400, 'Invalid requests, e.g. bad parameter.')
    @api.expect(base_endpoint_parser, validate=True)
    @api.marshal_with(json_api_single_response_model, skip_none=True, code=200)
    def get(self):
        """ Returns information relating to the API implementation- """
        base_request_args()

        result = {
            'type': 'info',
            'id': '/',
            'attributes': {
                'api_version': '0.10.0',
                'available_api_versions': [{
                    'url': url(),
                    'version': '0.10.0'
                }],
                'formats': ['json'],
                'entry_types_by_format': {
                    'json': ['calculations', 'info']
                },
                'available_endpoints': ['calculations', 'info'],
                'is_index': False
            }
        }

        return dict(
            meta=Meta(query=request.url, returned=1),
            data=result
        ), 200