Generate Clients

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

As FastAPI is based on the OpenAPI specification, you get automatic compatibility with many tools, including the automatic API docs (provided by Swagger UI).

One particular advantage that is not necessarily obvious is that you can generate clients (sometimes called SDKs ) for your API, for many different programming languages.

OpenAPI Client Generators

There are many tools to generate clients from OpenAPI.

A common tool is OpenAPI Generator.

If you are building a frontend, a very interesting alternative is openapi-typescript-codegen.

Generate a TypeScript Frontend Client

Let’s start with a simple FastAPI application:

Python 3.6+

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel
  3. app = FastAPI()
  4. class Item(BaseModel):
  5. name: str
  6. price: float
  7. class ResponseMessage(BaseModel):
  8. message: str
  9. @app.post("/items/", response_model=ResponseMessage)
  10. async def create_item(item: Item):
  11. return {"message": "item received"}
  12. @app.get("/items/", response_model=list[Item])
  13. async def get_items():
  14. return [
  15. {"name": "Plumbus", "price": 3},
  16. {"name": "Portal Gun", "price": 9001},
  17. ]
  1. from typing import List
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. price: float
  8. class ResponseMessage(BaseModel):
  9. message: str
  10. @app.post("/items/", response_model=ResponseMessage)
  11. async def create_item(item: Item):
  12. return {"message": "item received"}
  13. @app.get("/items/", response_model=List[Item])
  14. async def get_items():
  15. return [
  16. {"name": "Plumbus", "price": 3},
  17. {"name": "Portal Gun", "price": 9001},
  18. ]

Notice that the path operations define the models they use for request payload and response payload, using the models Item and ResponseMessage.

API Docs

If you go to the API docs, you will see that it has the schemas for the data to be sent in requests and received in responses:

Generate Clients - 图1

You can see those schemas because they were declared with the models in the app.

That information is available in the app’s OpenAPI schema, and then shown in the API docs (by Swagger UI).

And that same information from the models that is included in OpenAPI is what can be used to generate the client code.

Generate a TypeScript Client

Now that we have the app with the models, we can generate the client code for the frontend.

Install openapi-typescript-codegen

You can install openapi-typescript-codegen in your frontend code with:

Generate Clients - 图2

Generate Client Code

To generate the client code you can use the command line application openapi that would now be installed.

Because it is installed in the local project, you probably wouldn’t be able to call that command directly, but you would put it on your package.json file.

It could look like this:

  1. {
  2. "name": "frontend-app",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios"
  8. },
  9. "author": "",
  10. "license": "",
  11. "devDependencies": {
  12. "openapi-typescript-codegen": "^0.20.1",
  13. "typescript": "^4.6.2"
  14. }
  15. }

After having that NPM generate-client script there, you can run it with:

Generate Clients - 图3

That command will generate code in ./src/client and will use axios (the frontend HTTP library) internally.

Try Out the Client Code

Now you can import and use the client code, it could look like this, notice that you get autocompletion for the methods:

Generate Clients - 图4

You will also get autocompletion for the payload to send:

Generate Clients - 图5

Tip

Notice the autocompletion for name and price, that was defined in the FastAPI application, in the Item model.

You will have inline errors for the data that you send:

Generate Clients - 图6

The response object will also have autocompletion:

Generate Clients - 图7

FastAPI App with Tags

In many cases your FastAPI app will be bigger, and you will probably use tags to separate different groups of path operations.

For example, you could have a section for items and another section for users, and they could be separated by tags:

Python 3.9+Python 3.6+

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel
  3. app = FastAPI()
  4. class Item(BaseModel):
  5. name: str
  6. price: float
  7. class ResponseMessage(BaseModel):
  8. message: str
  9. class User(BaseModel):
  10. username: str
  11. email: str
  12. @app.post("/items/", response_model=ResponseMessage, tags=["items"])
  13. async def create_item(item: Item):
  14. return {"message": "Item received"}
  15. @app.get("/items/", response_model=list[Item], tags=["items"])
  16. async def get_items():
  17. return [
  18. {"name": "Plumbus", "price": 3},
  19. {"name": "Portal Gun", "price": 9001},
  20. ]
  21. @app.post("/users/", response_model=ResponseMessage, tags=["users"])
  22. async def create_user(user: User):
  23. return {"message": "User received"}
  1. from typing import List
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. price: float
  8. class ResponseMessage(BaseModel):
  9. message: str
  10. class User(BaseModel):
  11. username: str
  12. email: str
  13. @app.post("/items/", response_model=ResponseMessage, tags=["items"])
  14. async def create_item(item: Item):
  15. return {"message": "Item received"}
  16. @app.get("/items/", response_model=List[Item], tags=["items"])
  17. async def get_items():
  18. return [
  19. {"name": "Plumbus", "price": 3},
  20. {"name": "Portal Gun", "price": 9001},
  21. ]
  22. @app.post("/users/", response_model=ResponseMessage, tags=["users"])
  23. async def create_user(user: User):
  24. return {"message": "User received"}

Generate a TypeScript Client with Tags

If you generate a client for a FastAPI app using tags, it will normally also separate the client code based on the tags.

This way you will be able to have things ordered and grouped correctly for the client code:

Generate Clients - 图8

In this case you have:

  • ItemsService
  • UsersService

Client Method Names

Right now the generated method names like createItemItemsPost don’t look very clean:

  1. ItemsService.createItemItemsPost({name: "Plumbus", price: 5})

…that’s because the client generator uses the OpenAPI internal operation ID for each path operation.

OpenAPI requires that each operation ID is unique across all the path operations, so FastAPI uses the function name, the path, and the HTTP method/operation to generate that operation ID, because that way it can make sure that the operation IDs are unique.

But I’ll show you how to improve that next. 🤓

Custom Operation IDs and Better Method Names

You can modify the way these operation IDs are generated to make them simpler and have simpler method names in the clients.

In this case you will have to ensure that each operation ID is unique in some other way.

For example, you could make sure that each path operation has a tag, and then generate the operation ID based on the tag and the path operation name (the function name).

Custom Generate Unique ID Function

FastAPI uses a unique ID for each path operation, it is used for the operation ID and also for the names of any needed custom models, for requests or responses.

You can customize that function. It takes an APIRoute and outputs a string.

For example, here it is using the first tag (you will probably have only one tag) and the path operation name (the function name).

You can then pass that custom function to FastAPI as the generate_unique_id_function parameter:

Python 3.9+Python 3.6+

  1. from fastapi import FastAPI
  2. from fastapi.routing import APIRoute
  3. from pydantic import BaseModel
  4. def custom_generate_unique_id(route: APIRoute):
  5. return f"{route.tags[0]}-{route.name}"
  6. app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
  7. class Item(BaseModel):
  8. name: str
  9. price: float
  10. class ResponseMessage(BaseModel):
  11. message: str
  12. class User(BaseModel):
  13. username: str
  14. email: str
  15. @app.post("/items/", response_model=ResponseMessage, tags=["items"])
  16. async def create_item(item: Item):
  17. return {"message": "Item received"}
  18. @app.get("/items/", response_model=list[Item], tags=["items"])
  19. async def get_items():
  20. return [
  21. {"name": "Plumbus", "price": 3},
  22. {"name": "Portal Gun", "price": 9001},
  23. ]
  24. @app.post("/users/", response_model=ResponseMessage, tags=["users"])
  25. async def create_user(user: User):
  26. return {"message": "User received"}
  1. from typing import List
  2. from fastapi import FastAPI
  3. from fastapi.routing import APIRoute
  4. from pydantic import BaseModel
  5. def custom_generate_unique_id(route: APIRoute):
  6. return f"{route.tags[0]}-{route.name}"
  7. app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
  8. class Item(BaseModel):
  9. name: str
  10. price: float
  11. class ResponseMessage(BaseModel):
  12. message: str
  13. class User(BaseModel):
  14. username: str
  15. email: str
  16. @app.post("/items/", response_model=ResponseMessage, tags=["items"])
  17. async def create_item(item: Item):
  18. return {"message": "Item received"}
  19. @app.get("/items/", response_model=List[Item], tags=["items"])
  20. async def get_items():
  21. return [
  22. {"name": "Plumbus", "price": 3},
  23. {"name": "Portal Gun", "price": 9001},
  24. ]
  25. @app.post("/users/", response_model=ResponseMessage, tags=["users"])
  26. async def create_user(user: User):
  27. return {"message": "User received"}

Generate a TypeScript Client with Custom Operation IDs

Now if you generate the client again, you will see that it has the improved method names:

Generate Clients - 图9

As you see, the method names now have the tag and then the function name, now they don’t include information from the URL path and the HTTP operation.

Preprocess the OpenAPI Specification for the Client Generator

The generated code still has some duplicated information.

We already know that this method is related to the items because that word is in the ItemsService (taken from the tag), but we still have the tag name prefixed in the method name too. 😕

We will probably still want to keep it for OpenAPI in general, as that will ensure that the operation IDs are unique.

But for the generated client we could modify the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and cleaner.

We could download the OpenAPI JSON to a file openapi.json and then we could remove that prefixed tag with a script like this:

  1. import json
  2. from pathlib import Path
  3. file_path = Path("./openapi.json")
  4. openapi_content = json.loads(file_path.read_text())
  5. for path_data in openapi_content["paths"].values():
  6. for operation in path_data.values():
  7. tag = operation["tags"][0]
  8. operation_id = operation["operationId"]
  9. to_remove = f"{tag}-"
  10. new_operation_id = operation_id[len(to_remove) :]
  11. operation["operationId"] = new_operation_id
  12. file_path.write_text(json.dumps(openapi_content))

With that, the operation IDs would be renamed from things like items-get_items to just get_items, that way the client generator can generate simpler method names.

Generate a TypeScript Client with the Preprocessed OpenAPI

Now as the end result is in a file openapi.json, you would modify the package.json to use that local file, for example:

  1. {
  2. "name": "frontend-app",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios"
  8. },
  9. "author": "",
  10. "license": "",
  11. "devDependencies": {
  12. "openapi-typescript-codegen": "^0.20.1",
  13. "typescript": "^4.6.2"
  14. }
  15. }

After generating the new client, you would now have clean method names, with all the autocompletion, inline errors, etc:

Generate Clients - 图10

Benefits

When using the automatically generated clients you would autocompletion for:

  • Methods.
  • Request payloads in the body, query parameters, etc.
  • Response payloads.

You would also have inline errors for everything.

And whenever you update the backend code, and regenerate the frontend, it would have any new path operations available as methods, the old ones removed, and any other change would be reflected on the generated code. 🤓

This also means that if something changed it will be reflected on the client code automatically. And if you build the client it will error out if you have any mismatch in the data used.

So, you would detect many errors very early in the development cycle instead of having to wait for the errors to show up to your final users in production and then trying to debug where the problem is. ✨