HomeContact
Computerz
Generate a type annotated REST api client in python
René Dohmen
May 07, 2021
1 min

Today I was tasked with doing some REST API calls against a rather new FastAPI backend at SURF. The nice thing about FastAPI is that it uses OpenAPI which is a standard that describes the structure of REST requests and responses you can expect. Previously we were using some tools of Zalando for that; which involved writing rather big YAML files with the API specs. Other tooling was then used to generate a small backend with empty controllers and a client. It even works in quite some languages (PHP,Java, Ruby, Python). More info here.

So what’s the problem?

The generated clients are rather bulky and the generated backend for python uses Flask. Since my team, at SURF, migrated from Flask to FastAPI the openspecs are created direct from FastAPI. FastAPI comes with nice and strict, validated request and response schemes so it would be nice if the client would mimic that. So say “hi” to: openapi-python-client

You can create a new git repo, make a venv and install it:

Now create your client:

It will generate, type annotated python models for all encountered schemes and a other python module for each endpoint. Authentication, if correctly specified in the json is also honored, so you can do authenticated calls with a bit of luck without the to write code yourself.

This works for openapi v3. But what if you have an openapi v2 specification. I fiddled around with: https://api.improviser.education/swagger.json

Which returns

So I did run the api generator against it

openapi-python-client generate --path improviser.json

Note: I had to change the name in the downloaded .json to “improviser”. Originally it was “iMproviser API” which generated a very weird client name, something like i-improviser-client

You can see the resulting client in this repo

An example of what’s in the models can be found here


Related Posts

Working with git submodules
October 15, 2023
3 min
© 2024, All Rights Reserved.
Powered by formatics

Quick Links

Advertise with usAbout UsContact Us

Social Media