random-api is a small learning project that implements an API structure using FastAPI with OpenAPI 3.1
specifications for a simple Python package.
- The Python package (
random_api) is provided with metadata (metadata/all_variables.json) that specify the specs of all input variables used by the entrypointmain.entrypoint(). - The module
api_funcs.pyallows reading the metadata and creates a JSON schema compliant withOpenAPI 3.1specs. - The module
main_pydantic.pyusesapi_funcs.pyfunctions to create the JSON schema which is in turn used to buildpydanticmodels that are necessary for validating the API inputs. Thepydanticmodel declarations are written in a module namedpydantic_models.pystored underautomatically_generated. The name of this module is defined inconfig.py. - When launched, the script in
api.pyimports thepydanticmodels frompydantic_models.pywhich are then used to validate the user inputs when calling the endpoint/run.
-
Clone the repo from github
git clone git@github.com:RamiALBASHA/random-api.git cd random-api -
Install the package using
pippip install -e . -
Expose the API with
FastAPIanduvicornuvicorn random_api.api:app --reload --port 8080
-
Check out the doc in your browser
With Swagger UI: http://127.0.0.1:8080/docs
Alternative, with ReDoc documentation: http://127.0.0.1:8080/redoc
-
Check out the entrypoint endpoint
- Open a new terminal and call the endpoint with empty inputs, which will results in using the default values defined
in the
metadatafileall_variables.json:
curl -X POST http://127.0.0.1:8080/run -H "Content-Type: application/json" -d '{"stuff": {"a": 1, "b": 2}}'
You should get:
{"status":"success","result":{"done_this":0.5,"done_that":-1.0,"do_it":3}}- Alternatively, provide input values:
curl -X POST http://127.0.0.1:8080/run -H "Content-Type: application/json" -d '{"toto": -1, "tata": 1, "titi": 1, "param": 1, "stuff": {"a": 1, "b": 2}}'
- You should get:
{"status":"success","result":{"done_this":-1.0,"done_that":0.0,"do_it":3}}- Now test with unallowed values:
curl -X POST http://127.0.0.1:8080/run -H "Content-Type: application/json" -d '{"toto": -100, "stuff": {"a": 1, "b": 2}}'
You should get:
{"detail":[{"type":"greater_than_equal","loc":["body","toto"],"msg":"Input should be greater than or equal to -5","input":-100,"ctx":{"ge":-5}}]}You're done!
- Open a new terminal and call the endpoint with empty inputs, which will results in using the default values defined
in the